Você pode integrar aplicativos do Model Studio, como agentes, fluxos de trabalho ou orquestrações de agentes, aos seus sistemas de negócios usando o DashScope SDK ou HTTP.
Pré-requisitos
- Você tem uma chave de API. Consulte Obter uma chave de API.
- Você criou um aplicativo do Model Studio e obteve seu APP_ID (ID do aplicativo Model Studio). Ele está no cartão do aplicativo na página de gerenciamento de aplicativos.
Use o DashScope SDK ou uma interface HTTP para chamar um aplicativo do Model Studio.
Independentemente do método de chamada, configure a chave de API como variável de ambiente. Para usar o DashScope SDK, também é necessário instalá-lo.
Uso
Conversa de uma rodada
Exemplos de código para implementar uma conversa de uma rodada usando o DashScope SDK ou HTTP.
Python
Exemplo de solicitaçãoimport os
import dashscope
from dashscope.v2 import DashScopeError
# A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região.
client = dashscope.Client(
# Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID', # Substitua pelo ID real do aplicativo
prompt='Who are you?')
print(response.text)
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Exemplo de respostaI am a large language model developed by Alibaba Cloud, named Qwen. I am designed to help users generate various types of text, such as articles, stories, poems, stories, etc., and can be adjusted and optimized according to different scenarios and needs. In addition, I can also answer various questions, provide information and explanations, and assist in learning and research. If you have any needs, please feel free to ask me questions at any time!
Java
Exemplo de solicitação// Recommended dashscope SDK version >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Exemplo de respostatext: I am a large language model developed by Alibaba Cloud, named Qwen.
HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo.
{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am an AI assistant who can answer questions, create text, express opinions, and even write code. If you have any questions or need assistance, please don't hesitate to let me know, and I will do my best to provide you with the help you need."},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}%
PHP
Exemplo de solicitação<?php
# If the environment variable is not configured, you can replace the following line with your API Key: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with your actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize curl session
$ch = curl_init($url);
// Set curl options
curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
curl_setopt($ch, curlOPT_RETURNTRANSFER, true);
curl_setopt($ch, curlOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if curl execution was successful
if ($response === false) {
die("curl Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}}
else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Exemplo de respostaI am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen.
Node.js
Dependência:npm install axios
Exemplo de solicitaçãoconst axios = require('axios');
async function callDashScope() {
// If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Exemplo de respostaI am a large-scale language model developed by Alibaba Cloud, and my name is Qwen.
C#
Exemplo de solicitaçãousing System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "c274e14a58d9492f9baeffdc003a97c5",
"text": "I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am designed to assist users in generating various types of text, such as articles, stories, poems, etc., and can adapt and innovate according to different scenarios and needs. Additionally, I am capable of answering a wide range of questions, providing information and explanations, and helping users solve problems and acquire knowledge. If you have any questions or need assistance, please feel free to let me know anytime!"
},
"usage": {
"models": [
{
"output_tokens": 79,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "5c4b86b1-cd2d-9847-8d00-3fba8f187bc6"
}
Go
Exemplo de solicitaçãopackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "6105c965c31b40958a43dc93c28c7a59",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}
Conversa de várias rodadas
Em conversas de várias rodadas, o LLM pode consultar o histórico da conversa, aproximando a interação da comunicação cotidiana.
Atualmente, apenas aplicativos de agente e aplicativos de fluxo de trabalho de diálogo oferecem suporte a conversas de várias rodadas.
-
Ao passar
session_id, a solicitação inclui automaticamente o histórico da conversa armazenado na nuvem.Ao passar
session_id,prompté obrigatório. -
Você também pode manter um array
messages. Adicione o histórico de cada rodada e as novas instruções ao arraymessagese transmita o histórico por meio demessages.Ao passar
messages,prompté opcional. Se ambos forem passados,promptserá acrescentado ao final demessagescomo informação complementar.
Se
session_idemessagesforem passados juntos,messagesterá prioridade.
Armazenamento em nuvem (session_id)
Python
Exemplo de solicitaçãoimport os
import dashscope
from dashscope.v2 import DashScopeError
# A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região.
client = dashscope.Client(
# Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
def call_with_session():
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID', # Substitua pelo ID real do aplicativo
prompt='Who are you?')
responseNext = client.apps.completions.create(
app_id='YOUR_APP_ID', # Substitua pelo ID real do aplicativo
prompt='What skills do you have?',
session_id=response.session_id) # O session_id da resposta anterior
print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id))
# print('%s\n' % (response.usage))
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
if __name__ == '__main__':
call_with_session()
Exemplo de respostaI have multiple skills and can assist you with various tasks. Here are some of my main skills:
1. **Information retrieval**: Providing weather, news, historical facts, scientific knowledge, and various other information.
2. **Language processing**: Translating text, correcting grammar errors, generating articles and stories.
3. **Technical problem solving**: Answering programming questions, software usage, technical troubleshooting, etc.
4. **Educational assistance**: Helping with questions in subjects like mathematics, physics, chemistry, etc.
5. **Life advice**: Providing advice on health, diet, travel, shopping, etc.
6. **Entertainment interaction**: Telling jokes, playing word games, engaging in simple chat interactions.
7. **Schedule management**: Reminding important dates, arranging schedules, setting reminders.
8. **Data analysis**: Explaining data charts, providing data analysis suggestions.
9. **Emotional support**: Listening to your feelings, providing comfort and support.
If you have specific needs or questions, you can tell me directly, and I'll do my best to help you!
session_id=98ceb3ca0c4e4b05a20a00f913050b42
Java
Exemplo de solicitaçãoimport com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void callWithSession()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with the actual application ID
.appId("YOUR_APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("What skills do you have?");
result = application.call(param);
System.out.printf("%s\n, session_id: %s\n",
result.getOutput().getText(), result.getOutput().getSessionId());
}
public static void main(String[] args) {
try {
callWithSession();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Exemplo de respostaI possess multiple skills and can provide various types of assistance. Here are some of my main skills:
1. **Multilingual understanding and generation**: I can understand and generate text in multiple languages including Chinese and English.
2. **Information retrieval and synthesis**: I can search for relevant information based on your questions and organize and summarize it.
3. **Writing assistance**: Whether it's writing articles, reports, or creative writing, I can provide support.
4. **Programming assistant**: For programmers, I can help answer programming-related questions, provide code examples, etc.
5. **Educational guidance**: When encountering difficulties in the learning process, I can serve as an assistant to provide help, covering multiple subject areas from mathematics to history.
6. **Life advice**: I can also give some advice on issues related to healthy eating, travel planning, etc.
7. **Emotional communication**: Although I am an AI, I strive to communicate with you in a warm and supportive way.
If you have any specific needs or want to learn more about a particular aspect, please feel free to tell me!
, session_id: f2e94a980a34424fa25be45a7048d77c
HTTP
curl
Exemplo de solicitação (rodada 1)curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}
Exemplo de solicitação (rodada 2)curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What skills do you have?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "As an AI assistant, I have multiple skills that can help you complete various tasks, including but not limited to:
1. **Knowledge queries**: I can help you find information in various fields such as science, history, culture, technology, etc.
2. **Language translation**: I can help you translate text in different languages, supporting translation between multiple languages.
3. **Text generation**: I can generate articles, stories, poems, press releases, and various other types of text.
4. **Question answering**: Whether it's academic questions, common knowledge, or technical problems, I can try to provide answers for you.
5. **Conversational exchange**: I can have natural and smooth conversations with you, providing emotional support or entertainment.
6. **Code writing and debugging**: I can help you write code and solve problems in programming.
7. **Data analysis**: I can help you analyze data, provide statistical results and visualization suggestions.
8. **Creative inspiration**: If you need creative inspiration, such as design, advertising copy, marketing strategies, etc., I can also provide help.
If you have any specific needs or questions, feel free to tell me anytime!"
},
"usage": {
"models": [
{
"output_tokens": 208,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}
PHP
Exemplo de solicitação (rodada 1)<?php
# If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize curl session
$ch = curl_init($url);
// Set curl options
curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, curlOPT_POSTFIELDS, $dataString);
curl_setopt($ch, curlOPT_RETURNTRANSFER, true);
curl_setopt($ch, curlOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if curl execution was successful
if ($response === false) {
die("curl Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, curlINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
} else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";
}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";
} else {
echo "message=Unknown error\n";
}
}
?>
Exemplo de respostaI am a large-scale language model from Alibaba Cloud, my name is Qwen.
session_id=2e658bcb514f4d30ab7500b4766a8d43
Exemplo de solicitação (rodada 2)<?php
# If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => 'What skills do you have?',
// Replace with the session_id returned from the previous round of conversation
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize curl session
$ch = curl_init($url);
// Set curl options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if curl execution was successful
if ($response === false) {
die("curl Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
} else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";
}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";
} else {
echo "message=Unknown error\n";
}
}
?>
Exemplo de respostaI have multiple skills, including but not limited to:
1. **Multilingual capability**: I can understand and generate text content in multiple languages.
2. **Writing and creation**: Help with writing articles, stories, poems, and other creative content.
3. **Knowledge Q&A**: Answer common and professional questions from various fields.
4. **Code writing and understanding**: Able to write simple program code, and help explain or debug code.
5. **Logical reasoning**: Solve problems and puzzles that require logical thinking.
6. **Emotional support**: Provide positive psychological support and encouragement.
7. **Games and entertainment**: Participate in word games or other forms of interactive entertainment activities.
My goal is to be your capable assistant, providing help and support when you need it. If you have any specific needs or features you'd like to try, please feel free to tell me!
session_id=2e658bcb514f4d30ab7500b4766a8d43
Node.js
Dependência:npm install axios
Exemplo de solicitação (rodada 1)const axios = require('axios');
async function callDashScope() {
// If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Exemplo de respostaI am Qwen, an artificial intelligence assistant developed by Alibaba Cloud. I can answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
Exemplo de solicitação (rodada 2)const axios = require('axios');
async function callDashScope() {
// If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Replace session_id with the actual session_id from the previous conversation
const data = {
input: {
prompt: "What skills do you have?",
session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Exemplo de respostaI have various skills that can help you handle different tasks and questions. Here are some of my main skill areas:
1. **Information query and retrieval**: I can help find specific information, data, or news.
2. **Writing and creation**: Including writing articles, stories, poems, reports, etc.
3. **Language translation**: Can provide translation services between different languages.
4. **Educational tutoring**: Answer academic questions, help understand complex concepts.
5. **Technical support**: Solve technical problems encountered in computer use.
6. **Life advice**: Provide advice on health, diet, travel, and other aspects.
7. **Entertainment interaction**: Tell jokes, play word games, and other relaxing activities.
If you have specific needs or want to learn more about a particular aspect, please let me know!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
C#
Exemplo de solicitação (rodada 1)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}
Exemplo de solicitação (rodada 2)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""What skills do you have?"",
""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "I have multiple skills and can:
- Answer knowledge questions from a wide range of fields
- Provide learning resources and suggestions
- Assist with technical problems
- Communicate in multiple languages
- Help plan trips and activities
- Provide practical advice for daily life
If you have any specific needs or questions, feel free to let me know!"
},
"usage": {
"models": [
{
"output_tokens": 70,
"model_id": "qwen-plus",
"input_tokens": 123
}
]
},
"request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}
Go
Exemplo de solicitação (rodada 1)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}
Exemplo de solicitação (rodada 2)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "What skills do you have?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the actual session_id from the previous conversation
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}```
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "I have multiple skills and can:
- Answer various knowledge questions in fields such as science, history, culture, etc.
- Provide practical advice, such as travel tips, health tips, study methods, etc.
- Assist with text work, such as writing articles, editing documents, creating stories or poems.
- Perform multilingual translation, supporting translation between multiple languages.
- Have natural and smooth conversations with users, keeping them company, answering questions.
If you have any specific needs, feel free to let me know!"
},
"usage": {
"models": [
{
"output_tokens": 104,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}
Substitua YOUR_APP_ID pelo ID real do aplicativo. Na rodada 2, substitua
session_idpelo session_id retornado na rodada 1.
Gerenciamento próprio (messages)
Python
Exemplo de solicitação# A versão do SDK do DashScope deve ser 2.0.1 ou posterior.
import os
import dashscope
from dashscope.v2 import DashScopeError
# A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região.
client = dashscope.Client(
# Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'},
{"role": "assistant","content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."},
{"role": "user","content": "What can you do?"}
]
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID', # Substitua pelo ID real do aplicativo
messages=messages)
print('%s\n' % (response.text))
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Exemplo de respostaAs Qwen, I can help you complete various tasks, including but not limited to:
1. Answering questions: Whether it's scientific knowledge, technical problems, or common sense, I can provide accurate information and answers.
2. Creating text: Such as writing stories, poems, articles, etc., generating creative content based on given conditions.
3. Programming assistant: Can assist with programming learning, explain code logic, help debug program errors, etc.
4. Language translation: Support translation services between multiple languages.
5. Providing suggestions: Offering advice or solutions when facing decisions.
6. Emotional communication: Engaging in conversations with users, listening and giving positive responses and support.
In short, my goal is to be your capable assistant in work and life. If you have any specific needs, please feel free to tell me!
Java
Exemplo de solicitação// dashscope SDK version needs to be >= 2.17.0
import java.util.ArrayList;
import java.util.List;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
List messages = new ArrayList<>();
messages.add(Message.builder().role("system").content("You are a helpful assistant.").build());
messages.add(Message.builder().role("user").content("Who are you?").build());
messages.add(Message.builder().role("assistant").content("I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.").build());
messages.add(Message.builder().role("user").content("What can you do?").build());
ApplicationParam param = ApplicationParam.builder()
// If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.messages(messages)
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/error-code");
}
System.exit(0);
}
}
Exemplo de respostatext: I can help you complete various tasks, including but not limited to:
1. Answering questions: Whether academic questions, common knowledge, or questions in professional fields, I will do my best to provide accurate answers.
2. Creating text: Such as writing stories, official documents, emails, scripts, etc., just give me some basic information and requirements.
3. Table processing: Can help you organize data, generate or modify tables.
4. Code writing: Support code writing and explanation in multiple programming languages.
5. Multilingual translation: Can translate between different languages.
6. Simulated dialogue: Can play different roles to engage in simulated conversations with users.
If you have any specific needs, please feel free to tell me!
HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
},
{
"role": "assistant",
"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
},
{
"role": "user",
"content": "What can you do?"
}
]
},
"parameters": {},
"debug": {}
}'
Exemplo de resposta{"output":
{"finish_reason":"stop","session_id":"990ca89d89794826976d7499ad10cddb",
"text":"I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Whether academic knowledge, practical tips, or common sense questions, I will do my best to provide accurate answers.\n2. Creating text: Such as writing stories, official documents, emails, scripts, etc., as long as you tell me your specific needs, I can help you write them.\n3. Expressing opinions: For some subjective questions, I can also give my own views and discuss them with you.\n4. Games and entertainment: We can play word games together, or I can tell you a joke to help you relax.\n\nIn short, anything related to language, you can ask me for help!"},
"usage":{"models":[{"output_tokens":126,"model_id":"qwen-max","input_tokens":86}]},"request_id":"3908c4a3-8d7a-9e51-81a5-0fc366582990"}%
PHP
Exemplo de solicitação<?php
# If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
],
[
"role" => "assistant",
"content" => "I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen."
],
[
"role" => "user",
"content" => "What can you do?"
]
]
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize curl session
$ch = curl_init($url);
// Set curl options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check if curl execution was successful
if ($response === false) {
die("curl Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close curl session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
} else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";
}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";
} else {
echo "message=Unknown error\n";
}
}
?>
Exemplo de respostaI can help you complete various tasks, such as:
1. Answering questions: Whether academic questions, practical knowledge, or entertainment gossip, I will do my best to provide accurate answers.
2. Creating text: Including but not limited to writing stories, official documents, emails, etc.
3. Providing advice: Such as travel suggestions, learning methods, career planning, and other guidance and advice.
4. Engaging in conversation: We can chat, share feelings, and even have some interesting discussions.
If you need help with anything, just let me know!
Node.js
Dependência:npm install axios
Exemplo de solicitaçãoconst axios = require('axios');
async function callDashScope() {
// If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';//Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
"input": {
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
},
{
"role": "assistant",
"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
},
{
"role": "user",
"content": "What can you do?"
}
]
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Exemplo de respostaI can help you complete various tasks, including but not limited to:
1. Answering questions: Whether academic knowledge, practical information, or common sense questions, I will do my best to provide accurate answers.
2. Creating text: Such as writing stories, official documents, emails, scripts, etc., as long as you provide enough background information and requirements, I can help you write them.
3. Providing suggestions: If you need advice on certain decisions, such as travel destination selection, gift selection, study methods, etc., I can also provide suggestions based on your description.
4. Language translation: Support text translation between multiple languages.
5. Code writing and explanation: For programming-related questions, I can help write simple programs or explain complex concepts.
6. Engaging in conversation: In addition to the above functions, I can also have daily communication with users, sharing ideas.
If you have any specific needs, please feel free to tell me!
C#
Exemplo de solicitaçãousing System.Text;
class Program
{
static async Task Main(string[] args)
{
// If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace with the actual application ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""messages"": [
{{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
}},
{{
""role"": ""user"",
""content"": ""Who are you?""
}},
{{
""role"": ""assistant"",
""content"": ""I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.""
}},
{{
""role"": ""user"",
""content"": ""What can you do?""
}}
]
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "a6d041ca3d084a7ca9eff1c456afad70",
"text": "As Qwen, I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Providing answers to various knowledge-based questions.\n2. Text generation: Writing articles, stories, poems, and other text content.\n3. Language translation: Performing translation work between different languages.\n4. Conversational exchange: Having natural and smooth conversations with users.\n5. Providing suggestions: Offering suggestions or solutions based on user needs.\n\nIf you have any specific needs, please tell me, and I will do my best to help you."
},
"usage": {
"models": [
{
"output_tokens": 102,
"model_id": "qwen-max",
"input_tokens": 87
}
]
},
"request_id": "27fb8a01-70d5-974f-bb0a-e9408a9c1772"
}
Go
Exemplo de solicitaçãopackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Please make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"messages": []interface{}{
map[string]string{
"role": "system",
"content": "You are a helpful assistant.",
},
map[string]string{
"role": "user",
"content": "Who are you?",
},
map[string]string{
"role": "assistant",
"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.",
},
map[string]string{
"role": "user",
"content": "What can you do?",
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Exemplo de resposta{
"output": {
"finish_reason": "stop",
"session_id": "2ae51a5eac3b4b269834cf0695330a05",
"text": "I can help you complete various tasks, including but not limited to:\n\n1. Answering questions: Providing answers to knowledge-based questions in various fields.\n2. Text creation: Writing stories, articles, poems, etc.\n3. Programming assistant: Providing guidance and code examples for programming.\n4. Conversational chat: Engaging in daily conversations, keeping you company.\n5. Translation services: Providing translation support between multiple languages.\n6. Information queries: Finding news, weather forecasts, historical data, and other information.\n7. Learning guidance: Helping answer questions in learning, providing learning suggestions.\n\nIf you have any specific needs or questions, you can tell me, and I will do my best to help you!"
},
"usage": {
"models": [
{
"output_tokens": 132,
"model_id": "qwen-max",
"input_tokens": 87
}
]
},
"request_id": "1289eb09-e4ed-9f9e-98ca-805c83b333a1"
}
Passar parâmetros personalizados
Para adaptar o mesmo agente ou fluxo de trabalho a diferentes cenários, configure parâmetros personalizados para plug-ins ou nós e passe-os por biz_params ao chamar o aplicativo. Para saber como configurá-los, consulte Passagem de parâmetros de aplicativos. Exemplos:
-
Parâmetros de plug-ins personalizados: passe-os pelo aplicativo de agente associado ou pelo nó de plug-in do aplicativo de fluxo de trabalho associado.
Você pode passar parâmetros e informações de autenticação em nível de usuário para plug-ins personalizados:
- Parâmetros:
user_defined_params. - Autenticação em nível de usuário:
user_defined_tokens.user_tokencontém as informações de autenticação exigidas pelo plug-in, como DASHSCOPE_API_KEY.
O exemplo a seguir usa um aplicativo de agente que exige o parâmetro
indexe as informações de autenticação em nível de usuário do plug-in associado.Ferramentas de plug-in só podem ser associadas a aplicativos de agente do mesmo espaço de trabalho.
Substitua
your_plugin_codepelo ID da ferramenta de plug-in associada, exibido no cartão do plug-in, e passe os pares de chave e valor dos parâmetros de entrada. Neste exemplo,article_indextem o valor 2.Passagem de parâmetros
Python
Exemplo de solicitação
Exemplo de respostaimport os # A versão do SDK do DashScope deve ser 2.0.1 ou posterior. import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) biz_params = { # Passe os parâmetros de entrada personalizados de plug-in para aplicações de agente. Substitua your_plugin_code pelo ID do seu plug-in personalizado "user_defined_params": { "your_plugin_code": { "article_index": 2}}} try: response = client.apps.completions.create( app_id='YOUR_APP_ID', prompt='Dormitory convention content', biz_params=biz_params) print('%s\n' % (response.text)) # Processar para obter apenas a saída de texto # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')The second rule of the Dormitory Convention states: "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity." This indicates that within the dormitory, members should cultivate a positive atmosphere for living and studying, support and assist each other, and also learn to understand and respect one another. If you need to know about other clauses of the convention, please let me know!Java
Exemplo de solicitação
Exemplo de respostaimport com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = // Custom plug-in input parameter passing for agent applications, replace {your_plugin_code} with your custom plug-in ID "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}"; ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Dormitory convention content") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }Article Two of the Dormitory Convention stipulates: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. This emphasizes that within a shared living environment, roommates should maintain positive relationships and foster a harmonious atmosphere for living and studying through mutual assistance and support. If you need to know more specific clauses, please let me know.HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Dormitory convention content", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } } } }, "parameters": {}, "debug":{} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo.
{"output": {"finish_reason":"stop", "session_id":"e151267ffded4fbdb13d91439011d31e", "text":"The second article of the Dormitory Convention states: "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity." This implies that in dormitory life, everyone should support each other and jointly create a harmonious and positive living environment."}, "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]}, "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%PHP
Exemplo de solicitação
Exemplo de resposta<?php # If environment variables are not configured, replace with the Dashscope API Key: $api_key="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in production environments to reduce the risk of API Key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Replace {your_plugin_code} with the actual plugin ID // Construct request data $data = [ "input" => [ 'prompt' => 'Dormitory convention content', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [ 'article_index' => 2 ] ] ] ], ]; // Encode the data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute request $response = curl_exec($ch); // Check if curl execution succeeded if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close curl session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Article Two of the Dormitory Convention stipulates: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.This emphasizes that within a shared living environment, roommates should maintain positive relationships and foster a harmonious atmosphere for living and studying through mutual assistance and support. If you need to know more specific clauses, please let me know.Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Dormitory convention content", biz_params: { user_defined_params: { [pluginCode]: { // article_index is a variable for the custom plug-in, replace with the actual plug-in variable 'article_index': 3 } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();The third rule of the Dormitory Convention is as follows: Pay attention to electrical safety, and eliminate fire hazards. The use of open flames, unauthorized electrical appliances, various stoves, and other prohibited items is strictly forbidden in the dormitory. It is also forbidden to store explosive or flammable materials and to privately connect to the power supply. If you need to know more regulations, please let me know.C#
Exemplo de solicitação
Exemplo de respostausing System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string pluginCode = "{your_plugin_code}"; // Replace {your_plugin_code} with the actual plug-in ID string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory convention content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }{ "output": { "finish_reason": "stop", "session_id": "237ca6187c814f3b9e7461090a5f8b74", "text": "The second rule of the Dormitory Convention is as follows: "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.\" This indicates that within the dormitory, members need to establish positive relationships and create a harmonious living and learning environment through mutual assistance, caring, and support. It is also important to understand and accept differences among roommates and communicate sincerely. If there are other clauses or specific contents you want to know, please let me know!" }, "usage": { "models": [ { "output_tokens": 133, "model_id": "qwen-max", "input_tokens": 829 } ] }, "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79" }Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID if apiKey == "" { fmt.Println("Make sure you have set DASHSCOPE_API_KEY.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Dormitory convention content", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 2, }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }{ "output": { "finish_reason": "stop", "session_id": "860d2a4c1f3649ac880298537993cb51", "text": "The second rule of the Dormitory Convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. This emphasizes that in dormitory life, roommates should maintain good mutual assistance while also respecting each other. Would you like to know about other clauses?" }, "usage": { "models": [ { "output_tokens": 84, "model_id": "qwen-max", "input_tokens": 876 } ] }, "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab" }Autenticação em nível de usuário
Python
Exemplo de solicitação
Exemplo de respostaimport os # A versão do SDK do DashScope deve ser 2.0.1 ou posterior. import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) biz_params = { # Passe as informações de autenticação do plug-in personalizado para aplicações de agente. Substitua your_plugin_code pelo ID do seu plug-in personalizado e YOUR_TOKEN pelas informações de autenticação, como uma API Key "user_defined_params": { "your_plugin_code": { "article_index": 2}}, "user_defined_tokens": { "your_plugin_code": { "user_token": "YOUR_TOKEN"}}} try: response = client.apps.completions.create( app_id='YOUR_APP_ID', prompt='Dormitory convention content', biz_params=biz_params) print('%s\n' % (response.text)) # Processar para obter apenas a saída de texto # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')The second rule of the Dormitory Convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If you need further information on additional rules, please let me know.Java
Exemplo de solicitação
Exemplo de respostaimport com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = // Replace {your_plugin_code} with the actual plug-in ID, YOUR_TOKEN with the actual Token, such as API key "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," + "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}"; ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Dormitory convention content") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }The second rule of the Dormitory Convention says: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If you need further information on additional rules, please let me know.HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Dormitory convention content", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } }, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN" } } } }, "parameters": {}, "debug":{} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo.
{"output":{"finish_reason":"stop", "session_id":"d3b5c3e269dc40479255a7a02df5c630", "text":"The second article of the Dormitory Convention states: "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity." This implies that in dormitory life, everyone should support each other and jointly create a harmonious and positive living environment."}, "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]}, "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%PHP
Exemplo de solicitação
Exemplo de resposta<?php # If environment variables are not configured, replace with the Dashscope API Key: $api_key="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in production environments to reduce the risk of API Key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct the request data $data = [ "input" => [ 'prompt' => 'Dormitory convention content', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [// Replace {your_plugin_code} with the actual plugin ID 'article_index' => 2 ] ], 'user_defined_tokens' => [ '{your_plugin_code}' => [// Replace {your_plugin_code} with the actual plugin ID 'user_token' => 'YOUR_TOKEN'// Replace with the actual Token, such as API key ] ] ] ], ]; // Encode the data as JSON $dataString = json_encode($data); // Check if json_encode succeeded if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check if curl execution succeeded if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close curl session curl_close($ch); // Decode the response data $response_data = json_decode($response, true); // Handle the response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>The second rule of the Dormitory Convention is as follows: > Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If you need more information about the convention or other details, please feel free to let me know!Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Dormitory convention content", biz_params: { user_defined_params: { [pluginCode]: { // article_index is a variable for the custom plug-in, replace with the actual plug-in variable 'article_index': 6 } }, user_defined_tokens: { [pluginCode]: { // Replace YOUR_TOKEN with the actual authentication information, such as API key user_token: 'YOUR_TOKEN' } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();The sixth rule of the Dormitory Convention stipulates: Cultivate good habits regarding daily routines; every dormitory member has the right to rest and the responsibility to ensure others’ rights to rest. If you need more information on the regulations, please let me know.C#
Exemplo de solicitação
Exemplo de respostausing System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Make sure you have set DASHSCOPE_API_KEY."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string pluginCode = "your_plugin_code"; // Replace your_plugin_code with the actual plug-in ID // Replace YOUR_TOKEN with the actual Token, such as API key string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory convention content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }}, ""user_defined_tokens"": {{ ""{pluginCode}"": {{ ""user_token"": ""YOUR_TOKEN"" }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }{ "output": { "finish_reason": "stop", "session_id": "1a1913a9922a401f8eba36df8ea1a062", "text": "The second rule of the Dormitory Convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If there are other clauses or specific contents you want to know, please let me know!" }, "usage": { "models": [ { "output_tokens": 66, "model_id": "qwen-max", "input_tokens": 802 } ] }, "request_id": "04bac806-c5e6-9fab-a846-a66641862be9" }Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID if apiKey == "" { fmt.Println("Make sure you have set DASHSCOPE_API_KEY.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Dormitory convention content", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 10, }, }, "user_defined_tokens": map[string]interface{}{ pluginCode: map[string]interface{}{ "user_token": "YOUR_USER_TOKEN", // Replace with the actual authentication token, such as API key }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }{ "output": { "finish_reason": "stop", "session_id": "b8e051ba7e954ff8919208e7b84430fa", "text": "The tenth rule of the Dormitory Convention states that dormitory members should work together to create and maintain a clean, tidy, aesthetically pleasing, and culturally rich dormitory environment. If you need to understand the complete Dormitory Convention content, you may need to check other clauses or directly consult the dormitory management department. Is there any more specific content you would like to know?" }, "usage": { "models": [ { "output_tokens": 70, "model_id": "qwen-max", "input_tokens": 855 } ] }, "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14" } - Parâmetros:
-
Parâmetros de nós personalizados: passe-os pelo aplicativo de fluxo de trabalho, em seu nó inicial, ou pelo aplicativo de orquestração de agentes, em seu nó de aplicativo.
No exemplo a seguir, o aplicativo de fluxo de trabalho define um parâmetro
cityno nó inicial. Insira as variáveiscityequeryno Prompt e publique o aplicativo.
Ao chamar, passe
cityporbiz_paramsequeryporprompt.Python
Exemplo de solicitação
Exemplo de respostaimport os import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) # Passe parâmetros personalizados da aplicação de workflow ou de orquestração de agentes biz_params = {"city": "Hangzhou"} try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Substitua pelo ID real do aplicativo prompt='Query the administrative divisions of this city', biz_params=biz_params # Passe os parâmetros de negócio ) print(f'{response.text}') # Processar para obter apenas a saída de texto except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')The city of Hangzhou, as the capital of Zhejiang Province, has an administrative division consisting of 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own unique characteristics and development focus. - Shangcheng District: Located in the central area of Hangzhou, it is one of the political, economic, and cultural centers of the city. - Gongshu District: Known for its canal culture, it features numerous historical and cultural heritage sites. - Xihu District: Famous for the West Lake scenic area, it is an important destination for tourism. - Binjiang District: A hub for high-tech industries, with renowned companies like Alibaba situated here. - Xiaoshan District: An administrative district in the southeast, experiencing rapid economic growth, particularly in the manufacturing sector. - Yuhang District: Has developed rapidly in recent years, especially in the field of internet economy; Alibaba's headquarters is also located here (Note: Alibaba headquarters is actually in Binjiang District). - Linping District: A newly established district aimed at promoting comprehensive economic and social development in the area. - Qiantang District: Also a result of recent administrative adjustments, focusing on the integration of innovation and ecological protection. - Fuyang District: Located southwest of Hangzhou, known for its rich natural landscapes and long history and culture. - Lin'an District: Situated west of Hangzhou, famous for its beautiful ecological environment and profound cultural heritage. Please note that city planning may change over time, and it is recommended to refer to the latest official information.Java
Exemplo de solicitação
Exemplo de respostaimport com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"Hangzhou\"}"; ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Query the administrative divisions of this city") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }The city of Hangzhou is the capital of Zhejiang Province and its administrative division mainly includes 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own distinctive characteristics and development focuses. - Shangcheng District: Located in the city center of Hangzhou, it houses many historical and cultural heritage sites. - Gongshu District: Known for its Grand Canal culture, it is also an important commercial and residential area. - Xihu District: Famous for its beautiful natural scenery, including the renowned West Lake scenic area. - Binjiang District: A hub for high-tech industries, home to the Hangzhou National High-Tech Industry Development Zone. - Xiaoshan District: Experiences rapid economic growth, particularly outstanding in the manufacturing sector. - Yuhang District: Has rapidly risen in recent years following the development of high-tech companies like Alibaba. - Linping District: Formed in 2021 from parts of the original Yuhang District, it focuses on ecological construction and technological innovation. - Qiantang District: Also established as a new district in 2021, positioned as the eastern transportation hub and new industrial development area of Hangzhou. - Fuyang District: A cultural city with a long history and one of the important bases for the paper industry. - Lin'an District: Located in the western part of Hangzhou, known for its high forest coverage and good ecological environment. These districts together form the unique geographical layout and socio-economic structure of Hangzhou city. If you are interested in a particular district or need more detailed information, please let me know!HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Query the administrative divisions of this city", "biz_params": { "city": "Hangzhou"} }, "parameters": {} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo.
{ "output": { "finish_reason": "stop", "session_id": "c211219896004b50a1f6f66f2ec5413e", "text": "The city of Hangzhou has jurisdiction over 10 districts, 1 county, and manages 2 county-level cities, which are as follows: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District, Tonglu County, Chun'an County, Jiande City, Zhuji City. Note that Zhuji City is directly under the administration of Zhejiang Province and is jointly managed by both Hangzhou and Shaoxing cities." }, "usage": {}, "request_id": "02c3c9e1-7912-9505-91aa-248d04fb1f5d" }PHP
Exemplo de solicitação
Exemplo de resposta<?php # If environment variables are not configured, you can replace the following line with: $api_key="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leaks. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Query the administrative divisions of this city', 'biz_params' => [ 'city' => 'Hangzhou' ] ], ]; // Encode the data to JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get the HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the curl session curl_close($ch); // Decode the response data $response_data = json_decode($response, true); // Handle the response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n"; } echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n"; } else { echo "message=Unknown error\n"; } }Hangzhou is the capital city of Zhejiang Province and its administrative division mainly includes 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own unique characteristics and development focuses, such as: - **Shangcheng District** and **Gongshu District** are located in the center of Hangzhou, known for their bustling commerce and rich history. - **Xihu District** is famous for the beautiful West Lake and is also an important area for science, education, and culture. - **Binjiang District** is renowned for its high-tech industry development. - **Xiaoshan District** and **Yuhang District**, among others, have rapidly emerged as new urban districts or economic development zones due to recent city growth. - **Lin'an District** and **Fuyang District** have retained more of the natural scenery and rural charm. Please note that China's administrative divisions may change based on national policies, so please refer to official channels for the latest information.Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Query the administrative divisions of this city", biz_params: { 'city': 'Hangzhou', }, }, parameters: {}, debug: {}, }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Hangzhou is the capital city of Zhejiang Province, and its administrative division includes 10 districts, specifically: 1. **Shangcheng District (Shàngchéng Qū)**: Located in the southern part of central Hangzhou, it is one of the city's most historically rich and culturally significant areas. 2. **Gongshu District (Gǒngshù Qū)**: Originally formed from the merger of Xiacheng District and Gongshu District, situated in the northern part of Hangzhou. 3. **Xihu District (Xīhú Qū)**: Known for the World Heritage Site West Lake, featuring abundant natural and cultural landscapes. 4. **Binjiang District (Bīnjiāng Qū)**: Located on the southern bank of the Qiantang River, it is a hub for high-tech industries. 5. **Xiaoshan District (Xiāoshān Qū)**: Situated in the eastern part of Hangzhou, it is one of China's key manufacturing bases. 6. **Yuhang District (Yúháng Qū)**: Once home to Linping, one of China's four famous ancient towns, it has now grown into an important economic development zone in Hangzhou. 7. **Fuyang District (Fùyáng Qū)**: Located in the southwest of Hangzhou, named after the Fuchun River that flows through it. 8. **Lin'an District (Lín'ān Qū)**: Positioned in the mountainous western area of Hangzhou, renowned for its beautiful natural scenery. 9. **Qiantang District (Qiántáng Qū)**: Established in 2021, formed from the former Dajiangdong Industrial Cluster and parts of Xiaoshan District, aimed at fostering development in Hangzhou's eastern region. 10. **Linping District (Lín Píng Qū)**: A new administrative division separated from Yuhang District, mainly covering areas like Linping Street that were originally part of Yuhang District. This information reflects the situation as of my last update. Please note that administrative divisions may change, so refer to the official latest announcements for current information.C#
Exemplo de solicitação
Exemplo de respostausing System.Text; class Program { static async Task Main(string[] args) { //If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application ID string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = @"{ ""input"": { ""prompt"": ""Query the administrative divisions of this city"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": {}, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }{ "output": { "finish_reason": "stop", "session_id": "7a9ff57eec7d475fa5d487de5f5178d2", "text": "Hangzhou is the capital city of Zhejiang Province, and it has jurisdiction over 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its unique geographical locations and development features. For example, Xihu District is renowned for its beautiful natural scenery, especially the famous West Lake located there; while Binjiang District is more well-known for its high-tech industry development. Additionally, with the city's growth, the administrative divisions may undergo adjustments. Please refer to the latest official announcements for the most current information." }, "usage": { }, "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225" }Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Make sure you have set DASHSCOPE_API_KEY.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Query the administrative divisions of this city", "biz_params": map[string]interface{}{ "city": "Hangzhou", }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }{ "output": { "finish_reason": "stop", "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745", "text": "Hangzhou, abbreviated as 'Hang,' is the capital city of Zhejiang Province. According to the latest administrative division adjustments, Hangzhou now oversees 10 districts, 2 county-level cities, and 1 county, specifically: - Districts (10): Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District. - County-level Cities (2): Jiande City, Tonglu County (Note that Tonglu is actually treated as a county-level city here, but more accurately, it is a county). - County (1): Chun'an County. Please be aware that administrative regions may change over time, so please refer to the latest official announcements for the most current information. The above information is compiled based on relatively recent data; for the latest changes, visiting government official websites for the most accurate information is advised." }, "usage": { }, "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02" }
Saída em streaming
No modo de saída em streaming, o modelo gera resultados intermediários cuja concatenação forma o resultado final. Você pode ler o conteúdo à medida que é gerado, reduzindo a espera pela resposta. Conforme o método de chamada, configure os parâmetros abaixo para ativar o streaming:
- SDK Python: defina
streamcomo True. - SDK Java: chame pela interface
streamCall. - HTTP: especifique
X-DashScope-SSEcomoenableno cabeçalho.
Por padrão, a saída em streaming não é incremental: cada retorno inclui todo o conteúdo gerado até então. Para usar saída incremental em streaming, defina
incremental_output(incrementalOutputem Java) comotrue. Em HTTP, definaincremental_outputcomo true dentro do objeto parameters.
Exemplos:
-
Para aplicativos de agente:
Python
Exemplo de solicitação
Exemplo de respostaimport os import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: stream = client.apps.completions.create( app_id='YOUR_APP_ID', prompt='Who are you?', stream=True, # Habilite a saída em streaming incremental_output=True) # Habilite a saída incremental for partial in stream: print(f'{partial.text}\n') # Processar para obter apenas a saída de texto except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')I am Alibaba Cloud 's large-scale language model , my name is Qwen.Java
Exemplo de solicitação
Exemplo de resposta// Recommended dashscope SDK version >= 2.15.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import io.reactivex.Flowable;// Streaming output // Agent application implementation for streaming output results import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, replace the following line with: .apiKey("sk-xxx"). However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) // Replace with the actual application ID .appId("YOUR_APP_ID") .prompt("Who are you?") // Incremental output .incrementalOutput(true) .build(); Application application = new Application(); // .streamCall(): Streaming output content Flowable<ApplicationResult> result = application.streamCall(param); result.blockingForEach(data -> { System.out.printf("%s\n", data.getOutput().getText()); }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Please refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }I am Alibaba Cloud 's large-scale language model, my name is Qwen .HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --header 'X-DashScope-SSE: enable' \ --data '{ "input": { "prompt": "Who are you?" }, "parameters": { "incremental_output":true }, "debug": {} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo.
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":203,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"am"},"usage":{"models":[{"input_tokens":203,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":203,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":203,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"'s large-scale language"},"usage":{"models":[{"input_tokens":203,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":203,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":203,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}PHP
Exemplo de solicitação
Exemplo de resposta<?php // If environment variables are not configured, replace the following line with: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Who are you?'], "parameters" => [ 'incremental_output' => true]];// Incremental output // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, curlOPT_POSTFIELDS, $dataString); curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Don't return the transferred data curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) { echo $string; // Process streaming data return strlen($string); }); curl_setopt($ch, curlOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key, 'X-DashScope-SSE: enable' // Streaming output ]); // Execute request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE); // Close curl session curl_close($ch); if ($status_code != 200) { echo "HTTP Status Code: $status_code\n"; echo "Request Failed.\n"; } ?>id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"I am Alibaba"},"usage":{"models":[{"input_tokens":58,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":58,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"'s"},"usage":{"models":[{"input_tokens":58,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" a large-scale language"},"usage":{"models":[{"input_tokens":58,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":58,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":58,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}Node.js
Dependência:
Exemplo de solicitaçãonpm install axiosExpanda o painel para ver o exemplo de código:
Exemplo de resposta2. Exibir apenas o campo text
const axios = require('axios'); const { Transform } = require('stream'); async function callDashScope() { // If environment variables are not configured, replace the following line with: apiKey='sk-xxx'. However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Who are you?" }, parameters: { incremental_output: true }, // Incremental output debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-DashScope-SSE': 'enable' // Streaming output }, responseType: 'stream' // For handling streaming responses }); if (response.status === 200) { // // Process streaming response SSE protocol parsing transformer const sseTransformer = new Transform({ transform(chunk, encoding, callback) { this.buffer += chunk.toString(); // Split by SSE events (two line feeds) const events = this.buffer.split(/\n\n/); this.buffer = events.pop() || ''; // Keep incomplete part events.forEach(eventData => { const lines = eventData.split('\n'); let textContent = ''; // Parse event content lines.forEach(line => { if (line.startsWith('data:')) { try { const jsonData = JSON.parse(line.slice(5).trim()); if (jsonData.output?.text) { textContent = jsonData.output.text; } } catch(e) { console.error('JSON parsing error:', e.message); } } }); if (textContent) { // Add line feed and push this.push(textContent + '\n'); } }); callback(); }, flush(callback) { if (this.buffer) { this.push(this.buffer + '\n'); } callback(); } }); sseTransformer.buffer = ''; // Pipeline processing response.data .pipe(sseTransformer) .on('data', (textWithNewline) => { process.stdout.write(textWithNewline); // Automatic line feed output }) .on('end', () => console.log("")) .on('error', err => console.error("Pipeline error:", err)); } else { console.log("Request failed, status code:", response.status); response.data.on('data', chunk => console.log(chunk.toString())); } } catch (error) { console.error(`API call failed: ${error.message}`); if (error.response) { console.error(`Status code: ${error.response.status}`); error.response.data.on('data', chunk => console.log(chunk.toString())); } } } callDashScope();id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"Hello!"},"usage":{"models":[{"input_tokens":56,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" Is there"},"usage":{"models":[{"input_tokens":56,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" anything I can"},"usage":{"models":[{"input_tokens":56,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" help you with?"},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}I am Alibaba Cloud 's large-scale language model, I am called Qwen.C#
Exemplo de solicitação
Exemplo de respostausing System.Net; using System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, replace the following line with: apiKey="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application ID string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable"); string jsonContent = @"{ ""input"": { ""prompt"": ""Who are you"" }, ""parameters"": {""incremental_output"": true}, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); try { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = content; HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { Console.WriteLine("Request successful:"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); using (var stream = await response.Content.ReadAsStreamAsync()) using (var reader = new StreamReader(stream)) { string? line; // Declare as nullable string while ((line = await reader.ReadLineAsync()) != null) { if (line.StartsWith("data:")) { string data = line.Substring(5).Trim(); Console.WriteLine(data); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); } } } } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }2025-02-14 16:22:08:482 Request successful: 2025-02-14 16:22:09:098 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":51,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:099 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" am"},"usage":{"models":[{"input_tokens":51,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:172 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":51,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:172 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Cloud's large-scale language"},"usage":{"models":[{"input_tokens":51,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:463 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":51,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:618 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":51,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:777 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":". I am your AI"},"usage":{"models":[{"input_tokens":51,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:932 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" assistant,"},"usage":{"models":[{"input_tokens":51,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:091 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" I can answer questions,"},"usage":{"models":[{"input_tokens":51,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:244 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" create text, such as"},"usage":{"models":[{"input_tokens":51,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:389 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" writing stories, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":35,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:525 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" documents, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:662 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" emails, writing scripts"},"usage":{"models":[{"input_tokens":51,"output_tokens":43,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:902 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":", and I can also express"},"usage":{"models":[{"input_tokens":51,"output_tokens":47,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:062 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" opinions, play games, etc"},"usage":{"models":[{"input_tokens":51,"output_tokens":51,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:233 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:309 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:388Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "time" ) func main() { // If environment variables are not configured, replace the following line with: apiKey := "sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Please ensure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body, where incremental_output indicates whether to enable streaming response requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Who are you?", }, "parameters": map[string]interface{}{ "incremental_output": true, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers, where X-DashScope-SSE set to enable indicates enabling streaming response req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-DashScope-SSE", "enable") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) return } // Process streaming response reader := io.Reader(resp.Body) buf := make([]byte, 1024) for { n, err := reader.Read(buf) if n > 0 { data := string(buf[:n]) lines := strings.Split(data, "\n") for _, line := range lines { line = strings.TrimSpace(line) if len(line) >= 5 && line[:5] == "data:" { timestamp := time.Now().Format("2006-01-02 15:04:05.000") fmt.Printf("%s: %s\n", timestamp, line[5:]) } else if len(line) > 0 { fmt.Println(line) } } } if err != nil { if err == io.EOF { break } fmt.Printf("Error reading response: %v\n", err) break } } }id:1 event:result :HTTP_STATUS/200 2025-02-13 18:21:09.050: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":262,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:2 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Tong"},"usage":{"models":[{"input_tokens":262,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:3 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"yi"},"usage":{"models":[{"input_tokens":262,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id:4 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Qianwen, developed by"},"usage":{"models":[{"input_tokens":262,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:5 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Alibaba Cloud"},"usage":{"models":[{"input_tokens":262,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:6 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":", an AI assistant. I"},"usage":{"models":[{"input_tokens":262,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:7 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" am designed to answer"},"usage":{"models":[{"input_tokens":262,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:8 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.018: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" various questions, provide"},"usage":{"models":[{"input_tokens":262,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:9 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.102: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" information and engage"},"usage":{"models":[{"input_tokens":262,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:10 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.257: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" in conversations. Need"},"usage":{"models":[{"input_tokens":262,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:11 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.414: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" any help?"},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:12 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.481: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} -
O aplicativo de fluxo de trabalho oferece dois modos de saída em streaming, definidos por
flow_stream_mode.Valores dos parâmetros e métodos de uso:
-
full_thoughts(valor padrão):- Descrição: os resultados em streaming de todos os nós são retornados no campo
thoughts. - Requisito: também defina
has_thoughtscomo True.
- Descrição: os resultados em streaming de todos os nós são retornados no campo
-
agent_format:- Descrição: o mesmo modo de saída dos aplicativos de agente.
- Efeito: na console, ative a opção Resposta para um nó específico. Os resultados em streaming desse nó serão incluídos no campo
textdeoutput. - Cenário: adequado quando você precisa apenas da saída de determinados nós intermediários.
A opção Resposta está disponível somente nos nós de Conversão de Texto, LLM e Fim (ativada por padrão nos nós Fim). Nós sem suporte a streaming retornam todo o conteúdo de uma vez.
Exemplo:
full_thoughts
Este é um aplicativo de fluxo de trabalho publicado com saída em streaming.

Python
Exemplo de solicitação
Exemplo de respostaimport os import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) biz_params = { "city": "Hangzhou"} try: stream = client.apps.completions.create( # Substitua pelo ID real do aplicativo app_id='YOUR_APP_ID', prompt='Hello', biz_params=biz_params, # Habilite a saída em streaming stream=True, # incremental_output=true habilita a saída incremental, false desabilita; se não for especificado, o valor padrão é false incremental_output=True, # has_thoughts deve ser definido como True has_thoughts=True) for response in stream: print(f'{response.thoughts}\n') # A saída retorna apenas os thoughts; as informações do processo são retornadas no campo thoughts de output except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_99FA","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"Dongpo\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Pork, West Lake Vinegar Fish,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Longjing Shrimp, Hangzhou Pa\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"stry, Beggar\'s Chicken\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_qkYJ","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"West Lake,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Lingyin Temple, Xixi\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" National Wetland Park, Hefang\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Street, Hangzhou Botanical Garden\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_qkYJ","nodeExecTime":"1048ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"End","nodeResult":"{\\"result\\":\\"What do you think about our recommendation?\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]Java
Exemplo de solicitação
Exemplo de resposta// Recommended dashscope SDK version >= 2.15.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"Hangzhou\"}"; ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, replace the following line with: .apiKey("sk-xxx"). However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") //Replace with the actual application ID .prompt("Hello") .bizParams(JsonUtils.parse(bizParams)) .incrementalOutput(true) // Incremental output .hasThoughts(true) // For workflow applications to implement streaming output, this parameter must be set to true, and output results can be viewed in the thoughts field .build(); Application application = new Application(); Flowable<ApplicationResult> result = application.streamCall(param); // Implement streaming output result.blockingForEach(data -> { System.out.printf("%s\n",data.getOutput().getThoughts());// Process output to display only the thoughts field }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Please refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }[ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_S78u","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"West Lake Fish in Vinegar Sauce,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Longjing Shrimp\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\",Dongpo Pork,Zhiwei Small\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Steamed Buns,Beggar's\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Chicken\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_5ZzA","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"West Lake,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"Lingyin\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\" Temple,Songcheng\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\",Xixi Wetland,Thousand Island Lake\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_5ZzA","nodeExecTime":"938ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"End","nodeResult":"{\"result\":\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"5ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header 'X-DashScope-SSE: enable' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Hello", "biz_params": { "city": "Hangzhou"} }, "parameters": { "has_thoughts": true, "incremental_output": true }, "debug": {} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo.
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Ling\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"yin Temple,Songcheng,Xixi\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\" National Wetland Park,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Hangzhou Zoo\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1137ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}PHP
Exemplo de solicitação
Exemplo de resposta<?php # If environment variables are not configured, replace the following line with: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Hello', 'biz_params' => [ 'city' => 'Hangzhou' ] ], "parameters" => [ 'has_thoughts' => true, // For workflow applications and orchestration applications, this parameter must be set to true, and process information is returned in thoughts 'incremental_output' => true // Incremental output ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, curlOPT_POSTFIELDS, $dataString); curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Don't return the transferred data curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) { echo $string; // Process streaming data return strlen($string); }); curl_setopt($ch, curlOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key, 'X-DashScope-SSE: enable' // Fixed parameter for streaming output ]); // Execute request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE); // Close curl session curl_close($ch); if ($status_code != 200) { echo "HTTP Status Code: $status_code\n"; echo "Request Failed.\n"; } ?>id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Ilo9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"Dongpo Pork,Zhiwei Steamed\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"requestid:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_vQDv\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Hangzhou Tower\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"899ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with: apiKey='sk-xxx' using the Model Studio API Key. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "hello", biz_params:{ 'city':'Hangzhou' } }, parameters: { 'incremental_output' : 'true', 'has_thoughts':'true'//This parameter needs to be set for workflow applications and agent orchestration applications to implement streaming output }, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-DashScope-SSE': 'enable' }, responseType: 'stream' // Used to handle streaming response }); if (response.status === 200) { console.log("Request successful:"); // Handle streaming response response.data.on('data', (chunk) => { console.log(`Received chunk: ${chunk.toString()}`); }); response.data.on('end', () => { console.log("Stream ended."); }); response.data.on('error', (error) => { console.error(`Stream error: ${error.message}`); }); } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();/opt/homebrew/bin/node ./index.js Sending request to DashScope API... Request successful: Received chunk: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" in Vinegar Sauce,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng,Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"855ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Stream ended.C#
Exemplo de solicitação
Exemplo de respostausing System.Net; using System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, replace the following line with: apiKey="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application ID string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable"); string jsonContent = @"{ ""input"": { ""prompt"": ""Hello"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": { ""incremental_output"": true, ""has_thoughts"": true }, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); try { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = content; HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { Console.WriteLine("Request successful:"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); using (var stream = await response.Content.ReadAsStreamAsync()) using (var reader = new StreamReader(stream)) { string? line; // Declare as nullable string while ((line = await reader.ReadLineAsync()) != null) { if (line.StartsWith("data:")) { string data = line.Substring(5).Trim(); Console.WriteLine(data); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); } } } } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }2025-02-14 16:55:28:670 Request successful: 2025-02-14 16:55:28:980 {"output":{"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:28:980 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:28:980 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:29:178 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:29:780 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:29:979 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Zhiwei Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:30:179 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:30:379 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:30:986 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin Temple,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:31:180 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:31:382 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:31:751Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bufio" "bytes" "encoding/json" "fmt" "net/http" "os" ) func main() { apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Please ensure that DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "hello", "biz_params": map[string]interface{}{ "city": "Hangzhou", }, }, "parameters": map[string]interface{}{ "incremental_output": true, "has_thoughts": true, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-DashScope-SSE", "enable") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Printf("Error reading response: %v\n", err) } if resp.StatusCode != http.StatusOK { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) } }Request successful: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Vinegar\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Fish,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei Small\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Basket,Beggar's\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Qiandao Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:15 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}- Cada item de
thoughtscontém os detalhes de execução de um nó. A seguir está um exemplo de resultado de um nó LLM.
id:7 event:result :HTTP_STATUS/200 data: { "output": { "thoughts": [ { "response": "{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}" }, { "response": "{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Songcheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}" }, { "response": "{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}" } ], "session_id": "6035ee0814b64a9fb88346ecaf8b44bf", "finish_reason": "null" }, "usage": { "models": [ { "input_tokens": 25, "output_tokens": 21, "model_id": "qwen-max" } ] }, "request_id": "64825069-b3aa-93a7-bcf1-c66fe57111fd" }Para acompanhar os resultados em streaming de um nó LLM (LLM_j45e no exemplo acima), observe a saída do nó com nodeId LLM_j45e em cada envio de
thoughts.- Se um nó falhar, toda a tarefa também falhará.
agent_format
Este é um aplicativo de fluxo de trabalho publicado. A opção Resposta está ativada somente para o primeiro nó LLM, concentrando a saída nos resultados desse nó.

Python
Exemplo de solicitação
Exemplo de respostaimport os import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) biz_params = { "city": "Hangzhou"} try: stream = client.apps.completions.create( # Substitua pelo ID real do aplicativo app_id='YOUR_APP_ID', prompt='Hello', biz_params=biz_params, # Habilite a saída em streaming stream=True, # Habilite o modo de compatibilidade para gerar os resultados em streaming de nós especificados parameters={ "flow_stream_mode": "agent_format" }, # incremental_output=true habilita a saída incremental, false desabilita; se não for especificado, o valor padrão é false incremental_output=True) for partial in stream: print(f'{partial.text}\n') # Processar o texto de saída; os resultados são retornados no campo text except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')West Lake Fish in Vinegar Sauce, Longjing Shrimp ,Dongpo Pork ,Zhiwei Small Steamed Buns,Beggar's ChickenHTTP
curl
Exemplo de solicitação
Exemplo de respostacurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header 'X-DashScope-SSE: enable' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Hello", "biz_params": { "city": "Hangzhou"} }, "parameters": { "incremental_output": true, "flow_stream_mode": "agent_format" }, "debug": {} }'id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Fish in Vinegar"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":",Longjing Shrimp,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Pork,Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}PHP
Exemplo de solicitação
Exemplo de resposta<?php # If environment variables are not configured, replace the following line with: $api_key="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Hello', 'biz_params' => [ 'city' => 'Hangzhou' ] ], "parameters" => [ 'flow_stream_mode' => 'agent_format', // For workflow applications streaming output compatibility mode, set this parameter to agent_format 'incremental_output' => true // Incremental output ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, curlOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, curlOPT_POSTFIELDS, $dataString); curl_setopt($ch, curlOPT_RETURNTRANSFER, false); // Don't return the transferred data curl_setopt($ch, curlOPT_WRITEFUNCTION, function ($ch, $string) { echo $string; // Process streaming data return strlen($string); }); curl_setopt($ch, curlOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key, 'X-DashScope-SSE: enable' // Fixed parameter for streaming output ]); // Execute request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE); // Close curl session curl_close($ch); if ($status_code != 200) { echo "HTTP Status Code: $status_code\n"; echo "Request Failed.\n"; } ?>id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,Dongpo Pork,"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Zhiwei Steamed Buns,"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, replace the following line with: apiKey='sk-xxx'. However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Hello", biz_params:{ 'city':'Hangzhou' } }, parameters: { 'incremental_output' : 'true', "flow_stream_mode" : "agent_format" }, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-DashScope-SSE': 'enable' }, responseType: 'stream' // For handling streaming responses }); if (response.status === 200) { console.log("Request successful:"); // Process streaming response response.data.on('data', (chunk) => { console.log(`Received chunk: ${chunk.toString()}`); }); response.data.on('end', () => { console.log("Stream ended."); }); response.data.on('error', (error) => { console.error(`Stream error: ${error.message}`); }); } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Sending request to DashScope API... Request successful: Received chunk: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Zhiwei Steamed"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Stream ended.C#
Exemplo de solicitação
Exemplo de respostausing System.Net; using System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, replace the following line with: apiKey="sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application ID string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable"); string jsonContent = @"{ ""input"": { ""prompt"": ""Hello"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": { ""incremental_output"": true, ""flow_stream_mode"": ""agent_format"" }, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); try { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = content; HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { Console.WriteLine("Request successful:"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); using (var stream = await response.Content.ReadAsStreamAsync()) using (var reader = new StreamReader(stream)) { string? line; // Declare as nullable string while ((line = await reader.ReadLineAsync()) != null) { if (line.StartsWith("data:")) { string data = line.Substring(5).Trim(); Console.WriteLine(data); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); } } } } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }2025-02-14 17:17:09:408 Request successful: 2025-02-14 17:17:10:256 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:257 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,"},"usage":{"models":[{"input_tokens":25,"output_tokens":9,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:449 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"Beggar's Chicken,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:650 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Pork,Zhiwei Steamed Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:850 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bufio" "bytes" "encoding/json" "fmt" "net/http" "os" ) func main() { // If environment variables are not configured, replace the following line with: apiKey := "sk-xxx". However, it is not recommended to hardcode the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Please ensure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "Hello", "biz_params": map[string]interface{}{ "city": "Hangzhou", // Parameter passing }, }, "parameters": map[string]interface{}{ "incremental_output": true, // Setting this parameter to true enables incremental output of results "flow_stream_mode": "agent_format", // For workflow applications to implement streaming output in compatibility mode, this parameter needs to be set to agent_format }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-DashScope-SSE", "enable") // Streaming output requests need to set this parameter to enable // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Printf("Error reading response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) } }Request successful: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} -
Consultar a base de conhecimento
A base de conhecimento fornece a capacidade RAG do Model Studio e complementa os modelos com conhecimentos privados e recentes. Ao chamar aplicativos de agente, especifique o escopo da busca para melhorar a precisão das respostas.
Antes de começar
Na console do Model Studio, ative o Aprimoramento por busca na base de conhecimento no aplicativo de agente. Depois, publique o aplicativo.
Ignore esse pré-requisito para aplicativos RAG.
Especificar o escopo da busca
-
Para consultar uma base de conhecimento específica, escolha um dos métodos abaixo:
-
Na console, clique em Configurar base de conhecimento no aplicativo e selecione a base desejada. Depois, publique o aplicativo.
-
Não associe a base na console. Passe seu ID por
rag_optionsao fazer a chamada de API; -
Associe a base na console e passe seu ID por
rag_optionsao fazer a chamada de API.Nesse caso, apenas a base passada na chamada é consultada. Por exemplo, um aplicativo de agente está associado à base A, mas a chamada de API especifica a base B. Somente B será consultada; A não será.
Para obter o ID da base de conhecimento (pipeline_ids), acesse a página Base de conhecimento ou use
Data.Idretornado pela API CreateIndex. CreateIndex aceita apenas bases não estruturadas.Bailian Phones Specifications.docx é usado nos exemplos a seguir como base de conhecimento não estruturada.
Python
Exemplo de solicitação
Exemplo de respostaimport os # A versão do SDK do DashScope deve ser 2.0.1 ou posterior. import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Substitua YOUR_APP_ID pelo ID real do aplicativo prompt='Please recommend a mobile phone under 3000 yuan', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"], # Substitua pelos IDs reais das knowledge bases; separe múltiplos IDs com vírgulas } ) print('%s\n' % (response.text)) # Processar para obter apenas a saída de texto # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which fits your budget. It features a lightweight 6.4-inch 1080 x 2340 pixel screen design, paired with 128GB storage and 6GB RAM, suitable for daily use. Additionally, it has a 4000mAh battery and a lens that supports 30× digital zoom, which can meet your photography and battery life needs. If you're looking for a slim, portable phone with comprehensive features, the Bailian Zephyr Z9 would be a good choice.Java
Exemplo de solicitação
Exemplo de resposta// Recommended dashscope SDK version >= 2.16.8; import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import java.util.Collections; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with the actual application ID .prompt("Please recommend a mobile phone around 3000 yuan") .ragOptions(RagOptions.builder() // Replace with the actual specified knowledge base IDs, separate multiple with commas .pipelineIds(List.of("PIPELINES_ID1", "PIPELINES_ID2")) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text output only } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }Within your 3000 yuan budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499 and 2799, which fits your budget perfectly. It has the following features: - **Lightweight design**: The 6.4-inch screen is moderately sized, convenient for one-handed operation. - **Balanced performance**: Equipped with 128GB storage and 6GB RAM, which is sufficient for daily use. - **Battery life**: Features a 4000mAh battery that can meet your normal usage needs throughout the day. - **Photography capabilities**: Has a lens with 30× digital zoom, suitable for capturing distant scenery. If you're more focused on gaming experience or have other specific requirements, please let me know so I can provide more personalized recommendations!HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a mobile phone under 3000 yuan" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"]} }, "debug": {} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo e YOUR_PIPELINE_ID1 pelo ID da base de conhecimento desejada.
{"output":{"finish_reason":"stop","session_id":"d1208af96f9a4d8390e9b29e86f0623c", "text":"For a budget under 3000 yuan, I recommend the Bailian Zephyr Z9. This phone is priced between 2499 and 2799 yuan, perfectly fitting your budget requirement. It features a lightweight 6.4-inch 1080 x 2340 pixel display, paired with 128GB storage and 6GB RAM, sufficient for handling various applications and multitasking in daily use. Additionally, it comes with a 4000mAh battery, ensuring your usage throughout the day, and is equipped with a 30× digital zoom lens, allowing you to capture details in your life. In summary, the Bailian Zephyr Z9 is a good choice in terms of cost-effectiveness, design, and functionality."}, "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]}, "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}%PHP
Exemplo de solicitação
Exemplo de resposta<?php # If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Please recommend a smartphone under 3000 yuan.' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Replace with the specified knowledge base IDs; use commas to separate multiple IDs ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close curl session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n"; } echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n"; } else { echo "message=Unknown error\n"; } } ?>For a budget under 3000 yuan, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is perfect for your budget. It features a lightweight design with a 6.4-inch 1080 x 2340 pixel screen, 128GB storage and 6GB RAM, which can meet your daily usage needs well. Additionally, its 4000mAh battery ensures a full day of normal use, and it's equipped with a 30× digital zoom lens to capture distant details, making it both slim and powerful.Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a mobile phone under 3000 yuan" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // Replace with specified knowledge base IDs, separate multiple with commas } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();For a budget under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone has a reference price of 3999-4299 yuan, but if you can catch promotional activities or discounts, it might fall within your budget range. ### Bailian Zephyr Z9 - The Art of Lightweight Portability - **Screen**: 6.4-inch 1080 x 2340 pixels - **Storage and RAM**: 128GB storage / 6GB RAM - **Battery**: 4000mAh - **Camera**: 30× digital zoom lens This phone features a slim and portable design, very convenient for daily use, and has good battery life. If you're more concerned about value for money and daily user experience, the Bailian Zephyr Z9 is a good choice. If your budget is very strict, I suggest watching for promotional activities on e-commerce platforms, or considering other brands' phones in the same price range. Hope these suggestions are helpful!C#
Exemplo de solicitação
Exemplo de respostausing System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID // YOUR_PIPELINE_ID1 replace with specified knowledge base ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a mobile phone under 3000 yuan"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""] }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }{ "output": { "finish_reason": "stop", "session_id": "2344ddc540ec4c5fa110b92d813d3807", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone has a reference price between 2499-2799 yuan, which fits your budget requirements. It features a 6.4-inch 1080 x 2340 pixel screen, 128GB storage and 6GB RAM, which is sufficient for daily use. Additionally, the 4000mAh battery ensures normal use throughout the day, while the 30× digital zoom lens can meet your needs for capturing distant scenery. This is a slim, portable, and feature-rich choice." }, "usage": { "models": [ { "output_tokens": 121, "model_id": "qwen-max", "input_tokens": 1841 } ] }, "request_id": "99fceedf-2034-9fb0-aaad-9c837136801f" }Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Please make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a mobile phone under 3000 yuan", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified knowledge base ID }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }{ "output": { "finish_reason": "stop", "session_id": "fadbb4d1fe094ade88985620363506e6", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is very suitable for budgets under 3000 yuan. It features a lightweight 6.4-inch 1080 x 2340 pixel screen design, paired with 128GB storage and 6GB RAM, which can meet daily usage needs. At the same time, the 4000mAh battery ensures worry-free use throughout the day, while the 30× digital zoom lens can capture details from a distance, making it a very cost-effective choice." }, "usage": { "models": [ { "output_tokens": 119, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6" } -
-
Consulte documentos não estruturados específicos: passe o ID da base, os IDs dos documentos, as tags ou os metadados (pares de chave e valor) em
rag_options.IDs de documentos, tags e metadados são válidos apenas para documentos não estruturados.
-
Como obtê-los:
- ID do documento (file_ids): obtenha-o na página Dados do aplicativo ou use o ID retornado pela API AddFile ao importar documentos.
- Tags do documento: consulte-as na página Dados do aplicativo ou obtenha-as pela API DescribeFile.
- Metadados do documento: na página Base de conhecimento, clique em Exibir para abrir uma base e depois em Informações de metadados.
-
Você pode especificar vários IDs de documentos, desde que os documentos já estejam incluídos nos índices de conhecimento.
-
Ao especificar IDs de documentos, informe também o ID da base de conhecimento à qual pertencem.
-
Apenas os documentos especificados são consultados. Por exemplo, um aplicativo de agente está associado à base A, mas a chamada de API especifica documentos da base B. Apenas os documentos de B serão consultados, e não os de A.
Bailian Phones Specifications.docx é usado nos exemplos a seguir como base de conhecimento não estruturada.
Python
Exemplo de solicitação
Exemplo de respostaimport os # A versão do SDK do DashScope deve ser 2.0.1 ou posterior. import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Substitua YOUR_APP_ID pelo ID real do aplicativo prompt='Please recommend a mobile phone under 3000 yuan', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # Substitua pelos IDs reais das knowledge bases; separe múltiplos IDs com vírgulas "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"], # Substitua pelos IDs reais dos documentos não estruturados; separe múltiplos IDs com vírgulas "metadata_filter": { # Pares chave-valor de metadados dos documentos; separe múltiplos pares com vírgulas "key1": "value1", "key2": "value2" }, "tags": ["tag1", "tag2"] # Tags dos documentos; separe múltiplas tags com vírgulas } ) print('%s\n' % (response.text)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code'){ "text": "Within a budget of under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone has the following features: - **Screen**: 6.4-inch 1080 x 2340 pixels, suitable for daily use and entertainment. - **Memory and storage**: 6GB RAM + 128GB storage space, which can meet most users' needs for smoothness and storage. - **Battery capacity**: 4000mAh, providing all-day usage guarantee. - **Camera function**: Equipped with a lens supporting 30× digital zoom, capable of capturing details from greater distances. - **Other features**: Lightweight and portable design, easy to carry. The reference price is between 2499 and 2799 yuan, which perfectly fits your budget requirements and offers good value for money. Hope these suggestions are helpful!", "finish_reason": "stop", "session_id": "10bdea3d1435406aad8750538b701bee", "thoughts": null, "doc_references": null }Java
Exemplo de solicitação
Exemplo de resposta// Recommended dashscope SDK version >= 2.16.8; import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.google.gson.JsonObject; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject metadataFilter = new JsonObject(); metadataFilter.addProperty("key1", "value1"); // Metadata key-value pairs metadataFilter.addProperty("key2", "value2"); // For multiple, repeatedly call addProperty ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with the actual application ID .prompt("Please recommend a mobile phone around 3000 yuan") .ragOptions(RagOptions.builder() .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2")) // Replace with actual specified knowledge base IDs, separate multiple with commas .fileIds(List.of("FILE_ID1", "FILE_ID2")) // Replace with actual specified unstructured document IDs, separate multiple with commas .tags(List.of("tags1", "tags2")) // Replace with specified document tag IDs, separate multiple with commas .metadataFilter(metadataFilter) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text output only } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which fits perfectly within your budget range of around 3000 yuan. ### Bailian Zephyr Z9 Product Highlights: - **Screen**: 6.4-inch, 1080 x 2340 pixels, providing a clear and detailed visual experience. - **Storage and RAM**: 128GB storage space and 6GB RAM, sufficient to meet daily usage needs. - **Battery**: 4000mAh capacity battery can ensure normal use throughout the day. - **Camera**: Supports 30× digital zoom lens, capable of capturing distant details. - **Design**: Lightweight and portable, suitable for users who pursue fashion and convenience. This phone is not only moderately priced but also has balanced configurations and excellent appearance design, making it a very good choice in this price range. Hope these suggestions are helpful! If you have other requirements or questions, please feel free to let me know.HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a mobile phone around 3000 yuan" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"], "file_ids":["YOUR_FILE_ID1"], "metadata_filter":{ "name":"Alice"}, "tags":"mobile phone" } }, "debug": {} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo, YOUR_PIPELINE_ID1 pelo ID da base de conhecimento, YOUR_FILE_ID1 pelo ID do documento não estruturado e os pares de chave e valor de metadata_filter pelos metadados reais.
{"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d", "text":"Based on your budget, I recommend you consider the \"Tongyi Vivid 7\". It has a 6.5-inch 1080 x 2400 pixel full screen, with AI intelligent photography capabilities that allow you to take photos with professional-level color and detail. Its hardware configuration includes 8GB RAM and 128GB storage space, ensuring a smooth operating experience; the 4500mAh battery capacity also meets daily usage needs well. Additionally, the side fingerprint unlock design is both convenient and secure. The reference price is between 2999 and 3299 yuan, which fits your budget range."}, "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]}, "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%PHP
Exemplo de solicitação
Exemplo de resposta<?php # If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Please help me recommend a smartphone under 3000 yuan.' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with the specified knowledge base IDs; use commas to separate multiple IDs 'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'], // Replace with the actual document IDs; use commas to separate multiple IDs "metadata_filter" => [ // Metadata key-value pairs "key1" => "value1", "key2" => "value2" ], "tags" => ["Tag1", "Tag2"] // Document tags ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close curl session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n"; } echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n"; } else { echo "message=Unknown error\n"; } } ?>Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone has a reference price between 2499-2799 yuan, which is perfect for requirements under 3000 yuan. It features a lightweight 6.4-inch 1080 x 2340 pixel design, paired with 128GB storage and 6GB RAM, which can meet your daily usage needs. Additionally, it is equipped with a 4000mAh battery to ensure worry-free use throughout the day, and has a 30× digital zoom lens to capture distant details, making it a thin yet powerful choice.Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with: apiKey='sk-xxx' using the Model Studio API Key. However, it is not recommended to hard code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a mobile phone under 3000 yuan" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with the specified knowledge base IDs, separate multiple IDs with commas file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // Replace with the specified file IDs, separate multiple IDs with commas metadata_filter:{ // Metadata key-value pairs, separate multiple pairs with commas 'key1':'value1', 'key2':'value2' }, tags: ['tag1', 'tag2'] // Document tags, separate multiple tags with commas } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Within a budget of under 3000 yuan, I recommend you consider the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan and features a slim, portable design with a 6.4-inch 1080 × 2340 pixel screen, 128GB storage, and 6GB RAM, which can meet your daily usage needs. Its 4000mAh battery ensures all-day usage, while the 30× digital zoom lens helps capture details from greater distances. Overall, this is a high-value option.C#
Exemplo de solicitação
Exemplo de respostausing System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID // YOUR_PIPELINE_ID1 replace with specified knowledge base ID, YOUR_FILE_ID1 replace with specified unstructured document ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a mobile phone under 3000 yuan"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""], ""file_ids"":[""YOUR_FILE_ID1""], ""metadata_filter"":{{ ""name"":""Alice"" }}, ""tags"":""mobile phone"" }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }{ "output": { "finish_reason": "stop", "session_id": "be9b5a1964fe41c9bbfd8674226bd238", "text": "Based on your budget, I recommend the **Bailian Zephyr Z9**. This phone is priced between 2499-2799 yuan, which is very suitable for budgets under 3000 yuan. ### Product highlights - **Slim design**: Features a 6.4-inch screen with 1080 x 2340 pixel resolution, with an exquisite appearance that's easy to carry. - **Balanced performance**: Equipped with 6GB RAM and 128GB storage space, capable of meeting daily usage needs. - **Long-lasting battery**: Built-in 4000mAh battery ensures your normal usage throughout the day is not affected. - **Excellent photography**: Supports 30× digital zoom function, easily capturing distant scenery or details. If you're looking for a smartphone with good value for money that can meet basic needs while also having certain features, then the Bailian Zephyr Z9 would be a good choice." }, "usage": { "models": [ { "output_tokens": 180, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "d0811195-0b3f-931e-90b8-323a65053d9c" }Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Please make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a mobile phone under 3000 yuan", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified unstructured knowledge base ID "file_ids": []string{"YOUR_FILE_ID1"}, // Replace with specified unstructured document ID "metadata_filter": map[string]string{ "name": "Alice", // Metadata key-value pairs }, "tags": "mobile phone", // Unstructured data document tags }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }{ "output": { "finish_reason": "stop", "session_id": "9de268b3d84748b5ac6321aba72b6ecd", "text": "Based on your budget, I recommend you consider the **Bailian Zephyr Z9**. This phone has a reference price of 2499-2799 yuan, which is very suitable for needs under 3000 yuan. It has the following features: - Lightweight 6.4-inch 1080 x 2340 pixel screen design. - Paired with 128GB storage and 6GB RAM, capable of meeting daily usage needs. - Equipped with a 4000mAh battery, ensuring normal use throughout the day. - The rear camera supports 30× digital zoom lens, capable of capturing distant details. If you don't have particularly high requirements for photography or gaming, then the Bailian Zephyr Z9 should be a good choice." }, "usage": { "models": [ { "output_tokens": 156, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "8940b597-92e1-9471-b4eb-896e563c479d" }
-
-
Consulte dados específicos de documentos estruturados: passe o ID da base de conhecimento e pares de chave e valor de "cabeçalho de dados estruturados + valor" em
rag_options.Obtenha os pares de chave e valor de dados estruturados (structured_filter): na página Base de conhecimento, clique em Exibir para abrir a base e depois em Exibir índice.
Python
Exemplo de solicitação
Exemplo de respostaimport os # A versão do SDK do DashScope deve ser 2.0.1 ou posterior. import dashscope from dashscope.v2 import DashScopeError # A configuração abaixo refere-se à região Singapura. Substitua {WorkspaceId} pelo ID do seu workspace. O valor de region varia conforme a região. client = dashscope.Client( # Se não estiver usando uma variável de ambiente, defina sua API Key diretamente (por exemplo, api_key="sk-xxx"). Entretanto, não é recomendado codificar a API Key diretamente no código em ambientes de produção, para reduzir o risco de vazamento da API Key. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Substitua YOUR_APP_ID pelo ID real do aplicativo prompt='Please recommend a mobile phone under 3000 yuan', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # Substitua pelos IDs reais das knowledge bases; separe múltiplos IDs com vírgulas "structured_filter": { # Pares chave-valor de dados estruturados, correspondentes aos dados estruturados; separe múltiplos pares com vírgulas "key1": "value1", "key2": "value2" } } ) print('%s\n' % (response.text)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code'){ "text": "I recommend the \"Bailian\" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information, such as performance, appearance, etc., please let me know.", "finish_reason": "stop", "session_id": "80a3b868b5ce42c8a12f01dccf8651e2", "thoughts": null, "doc_references": null }Java
Exemplo de solicitação
Exemplo de resposta// Recommended dashscope SDK version >= 2.16.8; import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.google.gson.JsonObject; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject structureFilter = new JsonObject(); structureFilter.addProperty("key1", "value1"); // Structured data key-value pairs structureFilter.addProperty("key2", "value2"); // For multiple, repeatedly call addProperty ApplicationParam param = ApplicationParam.builder() // If environment variables are not configured, you can replace the following line with .apiKey("sk-xxx"). However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with the actual application ID .prompt("Please recommend a mobile phone around 3000 yuan") .ragOptions(RagOptions.builder() .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2")) // Replace with actual specified knowledge base IDs, separate multiple with commas .structuredFilter(structureFilter) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text output only } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("Refer to: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }I recommend the "Bailian" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need to know more information about this phone, such as configuration, performance, etc., please let me know, and I will provide you with more detailed information.HTTP
curl
Exemplo de solicitaçãocurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Please recommend a mobile phone around 3000 yuan" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"], "structured_filter":{ "price":"2999"} } }, "debug": {} }'
Exemplo de respostaSubstitua YOUR_APP_ID pelo ID real do aplicativo e YOUR_PIPELINE_ID1 pelo ID da base de conhecimento desejada.
{"output":{"finish_reason":"stop","session_id":"d6bc4206f9cc4d368d534f8aa4e502bc", "text":"I recommend a mobile phone priced close to 3000 yuan:\n\n- **Bailian phone**, priced at 2999 yuan. \n\nThis phone offers good value for money and meets your budget requirements. If you need more detailed information about this phone or have other specific requirements (such as camera performance, processor model, etc.), please let me know, and I will try to provide more comprehensive information."}, "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%PHP
Exemplo de solicitação
Exemplo de resposta<?php # If the environment variable is not configured, you can replace the next line with your API key: $api_key="sk-xxx". However, it is not recommended to hardcode the API key directly into the code in a production environment to reduce the risk of API key leakage. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => 'Please help me recommend a smartphone under 3000 yuan.' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // Replace with the specified knowledge base IDs; use commas to separate multiple IDs "structured_filter" => [ // Structured data key-value pairs; use commas to separate multiple entries "key1" => "value1", "key2" => "value2" ] ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize curl session $ch = curl_init($url); // Set curl options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check if curl execution was successful if ($response === false) { die("curl Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close curl session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n"; } echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n"; } else { echo "message=Unknown error\n"; } } ?>I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information about this phone, please let me know.Node.js
Dependência:
Exemplo de solicitaçãonpm install axios
Exemplo de respostaconst axios = require('axios'); async function callDashScope() { // If environment variables are not configured, you can replace the following line with apiKey='sk-xxx'. However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application ID // YOUR_PIPELINE_ID1 replace with specified knowledge base ID, separate multiple knowledge base IDs with commas const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a mobile phone under 3000 yuan" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], structured_filter:{ 'key1':'value1', 'key2':'value2' } } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more details or have other specific requirements, please let me know!C#
Exemplo de solicitação
Exemplo de respostausing System.Text; class Program { static async Task Main(string[] args) { // If environment variables are not configured, you can replace the following line with apiKey="sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID // YOUR_PIPELINE_ID1 replace with specified knowledge base ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("Please make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a mobile phone under 3000 yuan"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""], ""structured_filter"":{{ ""price"":""2999"" }} }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }{ "output": { "finish_reason": "stop", "session_id": "108e9104568e44f1915fb3d3d44fdc92", "text": "I recommend the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other suggestions, please let me know." }, "usage": { "models": [ { "output_tokens": 38, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "d6d103f4-5c22-9782-9682-45d51a5607f9" }Go
Exemplo de solicitação
Exemplo de respostapackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If environment variables are not configured, you can replace the following line with apiKey := "sk-xxx". However, it is not recommended to hard-code the API Key directly into the code in a production environment to reduce the risk of API Key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("Please make sure DASHSCOPE_API_KEY is set.") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]string{ "prompt": "Please recommend a mobile phone under 3000 yuan", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // Replace with specified structured knowledge base ID "structured_filter": map[string]string{ "price": "2999", // Structured data key-value pairs }, }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Process response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }{ "output": { "finish_reason": "stop", "session_id": "9e0a031b51d1492e8b613ca391b445b0", "text": "I recommend you consider the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other recommendations, please let me know." }, "usage": { "models": [ { "output_tokens": 39, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54" }
Exibir informações
Exibir o processo de busca: ao chamar, adicione has_thoughts ao código e defina-o como True. O processo de busca será retornado no campo thoughts de output.
Exibir a origem da resposta: ative Mostrar origem na Configuração de busca do aplicativo de agente e publique o aplicativo. 
Referência da API
Para a lista completa de parâmetros, consulte Referência da API DashScope para aplicativos de fluxo de trabalho e agentes legados.
Códigos de erro
Se uma chamada falhar, consulte Códigos de erro para solucionar o problema.
Referências
- Para chamar um aplicativo RAG por API ou SDK com pouco código, consulte Criar rapidamente um aplicativo RAG com pouco código.
- Para selecionar modelos em um aplicativo, consulte Lista de modelos.
- Para criar e usar aplicativos, consulte Tipos de aplicativo.
- Para usar a ferramenta de engenharia de prompts em um aplicativo, consulte Engenharia de prompts.
FAQ
Como corrigir a exceção "java: package com.alibaba.dashscope.app does not exist" ao executar um exemplo de código Java?
- Verifique se os nomes de classes e pacotes nas instruções de importação estão corretos.
- Adicione a dependência: se você usa Maven ou Gradle, verifique se a dependência do DashScope Java SDK está em
pom.xmloubuild.gradlee usa a versão mais recente. Consulte o número da versão mais recente no Maven.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>Enter the latest version, e.g., 2.16.4</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Enter the latest version, e.g., 2.16.4'
- Atualize o SDK: versões antigas do DashScope Java SDK podem não conter os recursos ou classes necessários. Se a versão estiver desatualizada, altere o número da versão em
pom.xmloubuild.gradle.
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>Replace this with the latest version number</version>
</dependency>
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: 'Replace this with the latest version number'
-
Recarregue o projeto para aplicar as alterações.
-
Execute novamente o exemplo de código.
Se o problema persistir, procure casos semelhantes e soluções no fórum de desenvolvedores ou abra um chamado.