Request body app_idstring(Required) Application identifier. You can obtain the application ID on the application card of the Application Management page.
In the Java SDK, it is appId. When calling through HTTP, put the actual application ID into the URL to replace APP_ID.
promptstring(Required) The input instruction from the user, which is used to guide the application to generate a reply.
When calling through HTTP, put prompt into the input object.
session_idstring (Optional) The historical conversation identifier. When session_id is passed in, the request automatically carries the conversation history stored in the cloud. In this case, you must pass prompt. The ID automatically expires after 1 consecutive hour without any request.
In the Java SDK, it is setSessionId. When calling through HTTP, put session_id into the input object.
messagesarray(Optional) The context passed to the LLM, arranged in conversation order. When you use the messages parameter to implement multi-turn conversation, you do not need to pass prompt or session_id. If both session_id and messages are passed in, the LLM preferentially uses the content in messages and ignores session_id and prompt.
When calling through HTTP, put messages into the input object.
To use this parameter, the Python DashScope SDK must be at least 2.0.1, and the Java DashScope SDK must be at least 2.17.0.
Message types System Messageobject (Optional) The system message, used to set the role, tone, task objective, or constraints of the LLM. It is generally placed first in the messages array. Properties contentstring(Required) The system instruction, used to specify the model's role, behavior rules, response style, and task constraints. rolestring(Required) The role of the system message, fixed to system. User Messageobject(Required) The user message, used to pass questions, instructions, or context to the model. Properties contentstring(Required) The message content. Properties textstring(Required) The input text. rolestring(Required) The role of the user message, fixed to user. Assistant Messageobject (Optional) The model's reply. It is usually passed back to the model as context in multi-turn conversations. Properties contentstring(Required) The text content of the model reply. rolestring(Required) The role of the assistant message, fixed to assistant. workspace string (Optional) The business space identifier. Related document: Obtain the Workspace ID. Pass the workspace ID only when calling an application in a sub-business space.
When calling through HTTP, specify X-DashScope-WorkSpace in the Header.
stream boolean(Optional) Default value: False Whether to reply in streaming output mode. We recommend setting it to True, which improves the reading experience and reduces the timeout risk. Parameter values:
False (default): The model returns all generated content at once;
True (recommended): Output while generating. Each time a portion of content is generated, a data chunk is returned. You need to read these chunks one by one in real time to assemble the complete reply.
To implement streaming output in the Java SDK, call through the streamCall interface; to implement streaming output through HTTP, set X-DashScope-SSE to enable in the Header.
incremental_output boolean(Optional) Default value: False Whether to enable incremental output in streaming output mode. We recommend setting it to True, which improves the reading experience. Parameter values:
False (default): Each time, the entire sequence that has been generated so far is output, and the last output is the complete generated result.
I
I like
I like apple
I like apple.
True (recommended): Incremental output, that is, subsequent output does not contain the content already output. You need to read these fragments one by one in real time to obtain the complete result.
I
like
apple
.
In the Java SDK, it is incrementalOutput. When calling through HTTP, put incremental_output into the parameters object.
flow_stream_mode string(Optional) Default value: full_thoughts The streaming output mode of workflow applications. Related document: Streaming output. Parameter values:
-
message_format_plus(Recommended): Message enhanced mode.
In the workflow_message field, the execution process and results of all nodes are output, covering all node types. It returns the same data structure as message_format, but supports streaming push for all node types.
ImportantClient-side processing rules: For text nodes (OUTPUT / END text mode), message.content is an incremental delta and needs to be appended; for JSON nodes (LLM / Component / AgentGroup, etc.), message.content is a complete JSON snapshot and needs to be replaced as a whole. When node_is_completed=true, the node is marked as finished executing.
Sub-canvas node streaming: Nodes in the sub-canvas of loop nodes and batch processing nodes are also pushed in streaming mode, identified by the response field parent_node_id as the parent node they belong to.
ImportantNested sub-canvas is not supported: loop or batch processing nodes cannot be placed in the sub-canvas of loop or batch processing nodes.
In the Java SDK, it is FlowStreamMode.MESSAGE_FORMAT_PLUS.
-
message_format(Recommended): Message mode.
In the message field, the results of the specified nodes (process output node or end node) are output.
ImportantIn the console application, turn on the streaming output switch of the target node to stream back results; when it is not turned on, the final result of the node is returned at once.
In the Java SDK, it is FlowStreamMode.MESSAGE_FORMAT.
-
full_thoughts (default): Full thoughts mode.
NoteNot recommended for new business. We recommend using message_format or message_format_plus instead.
The results of all nodes are output in the thoughts field.
ImportantWhen using this mode, you must also set the has_thoughts parameter to True.
In the Java SDK, it is FlowStreamMode.FULL_THOUGHTS.
The Python SDK must be at least 2.0.1, and the Java SDK must be at least 2.22.23. When calling through HTTP, put flow_stream_mode into the parameters object.
biz_paramsobject (Optional) When the application passes parameters through custom variables, nodes, or plugins, use this field to pass them. Related documents: Call an agent application - Pass custom parameters, Invoke a workflow application - Pass custom parameters.
In the Java SDK, it is bizParams. When calling through HTTP, put biz_params into the input object.
For workflow applications, the custom variables of the start node are passed directly. Example: biz_params = {"city": "Hangzhou"}
Agent applications pass prompt variables or plugin variable parameters through the following fields: Properties user_prompt_params object (Optional) Indicates the custom prompt variable parameter information. Variable names within an application cannot be duplicated, with an upper limit of 10. Steps:
- Configure custom variables and reference them in the prompt in the application, and then publish the application.
- Pass the variable information through this parameter in the API call.
Example: biz_params ={
"user_prompt_params": {
"date": "March 3, 2025",
"city": "Hangzhou"
}
}
user_defined_params object (Optional) Indicates the custom plugin parameter information. Plugins added to an application cannot be duplicated, with an upper limit of 10. Properties tool_idstring (Optional) The plugin ID, which can be obtained on the plugin card. ${plugin_params}string(Optional) Multiple key-value pairs contained at the innermost level of the object. Each key-value pair represents the user-defined parameter name to be passed and its specified value. For example: "article_index": 2
Steps:
- Associate the specified plugin in the application, and publish the application.
- Pass the plugin information through this parameter in the API call.
You can provide multiple key-value pairs, where each key is the plugin's TOOL_ID and the value is the parameter object required by that plugin. Example: "user_defined_params": {
"<TOOL_ID>": {
"article_index": 2},
"<TOOL_ID>": {
"article_index": 8}
}
user_defined_tokens object(Optional) Indicates the user-level authentication information of the custom plugin. Plugins added to an application cannot be duplicated, with an upper limit of 10. Properties tool_idstring (Optional) The plugin ID, which can be obtained on the plugin card. It is passed through the <TOOL_ID> field. user_token string (Optional) Passes the user authentication information required by the plugin, such as the value of the actual DASHSCOPE_API_KEY. Steps:
- Associate the specified plugin in the application, and publish the application.
- Pass the plugin user-level authentication information through this parameter in the API call.
You can provide multiple key-value pairs, where each key is the plugin's TOOL_ID and the value is the user_token object. memory_id string (Optional) The long-term memory ID, created through CreateMemory. Related document: Long-term memory. NoteOnly agent applications support this parameter.
- Turn on the long-term memory switch in the application, and publish the application.
- When calling the application with the specified
memory_id, the system automatically builds and saves long-term memory based on user preference information.
- When you call later with the same
memory_id, the system restores these long-term memories and merges them with the latest user message for the model to process.
In the Java SDK, it is memoryId. When calling through HTTP, put memory_id into the input object.
has_thoughts boolean (Optional) Default value: False Whether to output the process of plugin calls and knowledge retrieval, or the thinking process of a model with thinking mode enabled, which can be viewed in the thoughts field. Parameter values:
- True: Output.
- False (default): Do not output.
In the Java SDK, it is hasThoughts. When calling through HTTP, put has_thoughts into the parameters object.
image_list array(Optional) The image list. It supports image URLs and Data URLs (Base64-encoded). An image and video understanding model must be selected in the application. The base64 encoded format can be constructed as a Data URL: data:[MIME_type];base64,{base64_image}. For detailed instructions and code examples, see the Visual understanding section to the right of this document. Scenarios:
- Image retrieval (agent applications): Retrieves a structured knowledge base containing image links based on the uploaded image link.
- Visual understanding: Analyzes image content through the visual understanding capability of Qwen-VL series models to implement question answering.
Related document: Upload files (documents, images, videos, or audio).
In the Java SDK, it is images. When calling through HTTP, put image_list into the input object.
file_list array(Optional) A list containing one or more file URLs. NoteOnly agent applications support this parameter. Related document: Upload files (documents, images, videos, or audio).
In the Java SDK, it is files. When calling through HTTP, put file_list into the input object.
The Python DashScope SDK must be at least 2.0.1, and the Java DashScope SDK must be at least 2.21.13.
rag_options object (Optional) Used to configure retrieval-related parameters, including but not limited to retrieving from the specified knowledge bases or documents. Related document: Retrieve knowledge base. NoteOnly agent applications support this parameter.
In the Java SDK, it is ragOptions. When calling through HTTP, put rag_options into the parameters object.
Properties pipeline_ids array(Required) A list containing one or more knowledge base IDs. The maximum is 5. Retrieves all documents in the specified knowledge base. How to obtain:
- Obtain the knowledge base ID on the Knowledge Base page;
- Or through
Data.Id returned by the CreateIndex API (only unstructured knowledge bases are supported).
In the Java SDK, it is pipelineIds.
file_idsarray(Optional) A list containing one or more unstructured document IDs. The maximum is 5. Retrieves the unstructured documents in the specified knowledge base. When passing in document IDs, you must also pass the knowledge base IDs to which these documents belong in the pipeline_ids field. How to obtain:
In the Java SDK, it is fileIds.
metadata_filterobject (Optional) Used to filter the metadata of unstructured documents. By specifying one or more key-value pairs, unstructured documents with this metadata in the specified knowledge base are retrieved. Prerequisites: When passing in metadata, you must also pass the knowledge base IDs to which the metadata belongs in the pipeline_ids field. How to view:
- Visit the Knowledge Base page and click View Details Meta Information on the knowledge base card to view it.
- Or obtain it through the ListChunks API.
This object consists of one or more key-value pairs: Combination logic: Different keys are combined with "AND" logic. For example, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] means filtering out documents whose author is "John.Doe" and whose source is "internal_wiki" or "public_docs".
In the Java SDK, it is metadataFilter.
tags array (Optional) A list containing one or more unstructured document tags. Retrieves unstructured documents that have these tags. How to view: structured_filter object (Optional) Used to perform metadata filtering on structured data. By specifying one or more key-value pairs, you can filter out document chunks that meet the conditions. How to view:
- On the Knowledge Base page, click View Details View Index on the knowledge base card to view it.
- Or obtain it through the ListChunks API.
This object consists of one or more key-value pairs:
Each key (column name) must have a corresponding value; filtering by column name only is not supported.
Combination logic: Different keys are combined with "AND" logic. For example, "year": 2024, "department": ["Engineering", "Product"] means filtering out document chunks whose year is 2024 and whose department is "Engineering" or "Product".
In the Java SDK, it is structuredFilter.
session_file_idsarray(Optional) A list containing one or more file IDs. The maximum is 10. NoteOnly agent applications support this parameter. When calling an agent application, pass the file IDs, and the system will extract the text content from the files as the content basis for LLM question answering. Related document: Upload files (documents, images, videos, or audio). ImportantThe session file ID must start with "file_session_" and the file status must be FILE_IS_READY. Otherwise, the call fails.
In the Java SDK, it is sessionFileIds.
The Python DashScope SDK must be at least 2.0.1, and the Java DashScope SDK must be at least 2.17.0.
model_idstring(Optional) The model name. NoteOnly agent applications support this parameter. When calling the API, you can pass the model name used for this call through this parameter. Priority: When the model_id passed through the API differs from the console configuration, the API parameter value takes precedence.
In the Java SDK, it is modelId. When calling through HTTP, put model_id into the parameters object.
The Java DashScope SDK must be at least 2.19.3.
enable_system_timeboolean (Optional) Default value: True Controls whether the model automatically obtains the current time (Beijing time). NoteOnly agent applications support this parameter. Parameter values:
- True (default): The current time is enabled, and the model can directly respond to real-time requests (such as "today's date").
- False: The current time is disabled. You need to manually pass in the time through custom variables. For example:
# Pass a custom time through user_prompt_params
biz_params ={
"user_prompt_params": {
"date": "March 3, 2025"
}
}
Scenarios:
- You need to customize the time source instead of relying on the current time.
- Avoid changes in model output caused by changes in the current time.
In the Java SDK, it is enableSystemTime. When calling through HTTP, put enable_system_time into the parameters object.
The Java DashScope SDK must be at least 2.19.3.
enable_web_searchboolean (Optional) Default value: false Whether the model uses internet search results as reference when generating a reply. NoteOnly agent applications support this parameter. Parameter values:
-
True: Internet search is enabled, and the model uses the search results as reference information when generating a reply.
NoteThe model decides on its own whether and when to trigger an internet search.
-
False (default): Disables internet search.
Priority:
-
If this parameter is not set during the call, the status of the in-app web search
switch takes precedence.
-
If enable_web_search is set during the call, the API parameter takes precedence.
Enabling the internet search feature may increase Token consumption.
In the Java SDK, it is enableWebSearch. When calling through HTTP, put enable_web_search into the parameters object.
The Java DashScope SDK must be at least 2.19.3.
dialog_roundinteger (Optional) The number of context rounds carried. NoteOnly agent applications support this parameter. Sets the maximum number of historical conversation rounds input to the model. The more rounds, the stronger the conversation relevance. Priority: When the dialog_round passed through the API differs from the console configuration, the API parameter value takes precedence.
In the Java SDK, it is dialogRound. When calling through HTTP, put dialog_round into the parameters object.
The Java DashScope SDK must be at least 2.19.3.
enable_thinking boolean (Optional) Default value: false This parameter is used to switch between thinking mode and non-thinking mode in deep thinking models. It applies only to agent applications. ImportantWorkflow applications do not support dynamically controlling the thinking mode through this parameter; you need to set it in each LLM node separately. Parameter values:
- False (default): Non-thinking mode. The final answer is returned directly (in the
text field).
- True: Thinking mode is enabled. The model first outputs the thinking process and then returns the final answer.
Priority:
- If this parameter is not set at the call, the thinking mode switch state of the model in the application takes precedence.
- If
enable_thinking is set at the call, the API parameter takes precedence.
ImportantTo obtain the content of the thinking process, you must also set has_thoughts to True. Then:
- Thinking process: for agent applications, obtain it through the
thought field; for workflow applications, obtain it through the reasoningContent field.
- Final answer: obtain it through the
text field.
There is a very small chance that the thinking process is not output even after enable_thinking is enabled.
In the Java SDK, this parameter is enableThinking. When you call the API over HTTP, put enable_thinking in the parameters object.
The Java DashScope SDK version must be 2.20.0 or later.
| Single-turn conversationPythonRequest exampleimport os
import dashscope
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace with the actual application ID
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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaRequest example// Recommended dashscope SDK version: 2.12.0 or later
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message:"+e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
Replace APP_ID with the actual application ID.
PHPRequest example<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Node.jsYou must install the following dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Request exampleusing System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope.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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the 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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
dashscope CLIRequest exampleexport DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with the workspace ID and cn-beijing with the appropriate region (Singapore: ap-southeast-1, US East: us-east-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
dashscope application create -a your-app-id -p "Hello"
Replace your-app-id with the actual application ID. -a specifies the application ID, and -p specifies the prompt content.
ImportantThe SDK Expert interactive assistant can complete the same development and troubleshooting work in natural language. See DashScope SDK Expert. For the complete region list, see Base URL overview. Multi-turn conversationEnable multi-turn conversations through session_id or messages. Related documents: Call an agent application - multi-turn conversation, Call a workflow application - multi-turn conversation. PythonRequest exampleimport os
import dashscope
from dashscope.v2 import DashScopeError
def call_with_session():
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace with the actual application ID
prompt='Who are you?')
responseNext = client.apps.completions.create(
app_id='APP_ID', # Replace with the actual application ID
prompt='What skills do you have?',
session_id=response.session_id) # session_id from the previous response
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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
if __name__ == '__main__':
call_with_session()
JavaRequest exampleimport 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;
public class Main {
public static void callWithSession()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with the actual application ID
.appId("APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("What skills do you have?");
result = application.call(param);
System.out.printf("%s\n session_id: %s\n",
result.getOutput().getText(), result.getOutput().getSessionId());
}
public static void main(String[] args) {
try {
callWithSession();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest example (previous turn)curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
Request example (next turn)curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What skills do you have?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHPRequest example (previous turn)<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";
};
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";}
}
?>
Request example (next turn)<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'What skills do you have?',
// Replace with the session_id returned by the previous turn
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.jsInstall the required dependencies:npm install axios
Request example (previous turn)const axios = require('axios');
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const url = `https://dashscope.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();
Request example (next turn)const axios = require('axios');
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Replace session_id with the actual session_id from the previous turn
const data = {
input: {
prompt: "What skills do you have?",
session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Request example (previous turn)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope.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}");
}
}
}
}
Request example (next turn)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope.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}");
}
}
}
}
GoRequest example (previous turn)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the 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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Request example (next turn)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the 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 turn
},
"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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Replace APP_ID with the actual application ID. In the next turn, replace the value of the session_id input parameter with the session_id value returned in the previous turn.
Pass parametersPass custom parameters through biz_params. Related documents: Call an agent application - Pass custom parameters, Invoke a workflow application - Pass custom parameters. PythonRequest exampleimport os
import dashscope
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
biz_params = {
# Pass custom plugin input parameters for the agent application; replace the custom plugin ID with <TOOL_ID>
"user_defined_params": {
"<TOOL_ID>": {
"article_index": 2}}}
try:
response = client.apps.completions.create(
app_id='APP_ID',
prompt='Dormitory agreement content',
biz_params=biz_params)
print('%s\n' % (response.text)) # Handle text-only output
# 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaRequest exampleimport 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;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
// Pass custom plugin input parameters for the agent application; replace the custom plugin ID with <TOOL_ID>
"{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("Dormitory agreement content")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Dormitory agreement content",
"biz_params":
{
"user_defined_params":
{
"<TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace APP_ID with the actual application ID. Replace <TOOL_ID> with the plugin ID.
PHPRequest example<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Replace <TOOL_ID> with the actual plugin ID
// Build the request data
$data = [
"input" => [
'prompt' => 'Dormitory agreement content',
'biz_params' => [
'user_defined_params' => [
'<TOOL_ID>' => [
'article_index' => 2
]
]
]
],
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Node.jsInstall the required dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const pluginCode = 'TOOL_ID';// Replace with the actual plugin ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Dormitory agreement content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index is a custom plugin variable; replace it with the actual plugin variable
'article_index': 3
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Request exampleusing System.Text;
class Program
{
static async Task Main(string[] args)
{
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID";// Replace with the actual application ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "TOOL_ID"; // Replace TOOL_ID with the actual plugin ID
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Dormitory agreement 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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
pluginCode := "TOOL_ID" // Replace with the actual plugin ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "Dormitory agreement 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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Impact of releasing a new version on API callsAfter you release a new version of an application, the APP_ID always points to the latest released version. Requests in progress at release time are not interrupted and complete normally based on the pre-release configuration; after the release is complete, new requests initiated through the same APP_ID use the new version's configuration (including the prompt, model, tools, and so on). The API does not support specifying a historical version to call through parameters. The request body contains only the input and parameters fields, and does not provide a version number or historical version parameter. If the session_id of a multi-turn conversation continues to be used after a new version is released, context understanding deviations or tool call exceptions may occur, because the historical context of that session was generated based on the pre-release configuration. We recommend ending active multi-turn conversations before releasing major changes, or starting a new session with a new session_id after the release. To restore the pre-release configuration, perform a version rollback on the application details page in the Alibaba Cloud Model Studio console:
- Click Version management.
- Select the historical version to restore.
- Click Overwrite current draft.
- Click Release to make the rollback take effect.
To reduce the impact on live calls, we recommend releasing major changes during off-peak business hours; if you need to provide multiple versions of capabilities externally at the same time, you can manage versions by creating multiple applications (using different APP_IDs). Streaming outputStreaming output is implemented through stream. Related documents: Call an agent application - streaming output, Call a workflow application - streaming output. PythonRequest exampleimport os
import dashscope
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
stream = client.apps.completions.create(
app_id='APP_ID',
prompt='Who are you?',
stream=True, # streaming output
incremental_output=True) # Incremental output
for partial in stream:
print(f'{partial.text}\n') # Handle text-only output
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaRequest example// Recommended dashscope SDK version: 2.15.0 or later
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// streaming output
// Implement streaming output for an agent application call
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with the actual application ID
.appId("APP_ID")
.prompt("Who are you?")
// Incremental output
.incrementalOutput(true)
.build();
Application application = new Application();
// .streamCall(): streaming output content
Flowable<ApplicationResult> result = application.streamCall(param);
result.blockingForEach(data -> {
System.out.printf("%s\n",
data.getOutput().getText());
});
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
Replace APP_ID with the actual application ID.
PHPRequest example<?php
// If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'Who are you?'],
"parameters" => [
'incremental_output' => true]];// Incremental output
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return 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 the request
$response = curl_exec($ch);
// Check whether the cURL request succeeded
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 handle
curl_close($ch);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Node.jsYou need to install the following dependencies:npm install axios
Request example1. Output the complete response const axios = require('axios');
async function callDashScope() {
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const url = `https://dashscope.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 the streaming response
response.data.on('data', (chunk) => {
console.log(`Received chunk: ${chunk.toString()}`);
});
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
You can expand the collapsible panel to view the specific content: 2. Output only the content of the text field const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID'; // Replace with the actual application ID
const url = `https://dashscope.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 the streaming response; parse and convert the SSE stream
const sseTransformer = new Transform({
transform(chunk, encoding, callback) {
this.buffer += chunk.toString();
// Split by SSE events (two newlines)
const events = this.buffer.split(/\n\n/);
this.buffer = events.pop() || ''; // Keep the incomplete part
events.forEach(eventData => {
const lines = eventData.split('\n');
let textContent = '';
// Parse the 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 parse error:', e.message);
}
}
});
if (textContent) {
// Add a newline and push
this.push(textContent + '\n');
}
});
callback();
},
flush(callback) {
if (this.buffer) {
this.push(this.buffer + '\n');
}
callback();
}
});
sseTransformer.buffer = '';
// Pipe processing
response.data
.pipe(sseTransformer)
.on('data', (textWithNewline) => {
process.stdout.write(textWithNewline); // Output with automatic line breaks
})
.on('end', () => console.log(""))
.on('error', err => console.error("Pipe error:", err));
} else {
console.log("Request failed, status code:", response.status);
response.data.on('data', chunk => console.log(chunk.toString()));
}
} catch (error) {
console.error(`API call failed: ${error.message}`);
if (error.response) {
console.error(`Status code: ${error.response.status}`);
error.response.data.on('data', chunk => console.log(chunk.toString()));
}
}
}
callDashScope();
C#Request exampleusing System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope.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 a 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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body; incremental_output controls whether streaming is enabled
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 the 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 the request headers; set X-DashScope-SSE to enable to turn on streaming
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-DashScope-SSE", "enable")
// Send the 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 the 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
}
}
}
Retrieve knowledge baseWhen you call an agent application, you can use rag_options to implement knowledge base retrieval. Related document: Retrieve a knowledge base. PythonRequest exampleimport os
import dashscope
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace APP_ID with the actual application ID
prompt='Recommend a phone under 3,000 yuan',
rag_options={
"pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"], # Replace with the actual knowledge base IDs, separated by commas
}
)
print('%s\n' % (response.text)) # Handle text-only output
# 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaRequest example// Recommended dashscope SDK version: 2.16.8 or later;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with the actual application ID
.prompt("Recommend a phone around 3,000 yuan")
.ragOptions(RagOptions.builder()
// Replace with the specified knowledge base IDs, separated by commas
.pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Handle text-only output
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Recommend a phone under 3,000 yuan"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["PIPELINE_ID1"]}
},
"debug": {}
}'
Replace APP_ID with the actual application ID, and replace PIPELINE_ID1 with the specified knowledge base ID.
PHPRequest example<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'Recommend a phone under 3,000 yuan'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//Replace with the specified knowledge base IDs, separated by commas
]
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Node.jsInstall the required dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';//Replace with the actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Recommend a phone under 3,000 yuan"
},
parameters: {
rag_options:{
pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2'] // Replace with the specified knowledge base IDs, separated by 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();
C#Request exampleusing System.Text;
class Program
{
static async Task Main(string[] args)
{
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID";// Replace with the actual application ID
// Replace PIPELINE_ID1 with the specified knowledge base ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Recommend a phone under 3,000 yuan""
}},
""parameters"": {{
""rag_options"" : {{
""pipeline_ids"":[""PIPELINE_ID1""]
}}
}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Recommend a phone under 3,000 yuan",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"pipeline_ids": []string{"PIPELINE_ID1"}, // Replace with the 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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
To view retrieval process information: add has_thoughts to your code and set it to True when you make the call. The retrieval process information will then be returned in the thoughts field of the response. Long-term memoryWhen you call an agent application, specify memory_id to enable long-term memory. Related document: Long-term memory. PythonRequest example (generate memory content)# Requires dashscope 2.0.1 or later
import os
import dashscope
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Enter the actual application ID
prompt='User dietary preference: noodles',
memory_id='MEMORY_ID') # Enter the actual memory ID
print('%s\n' % (response.text)) # Handle text-only output
# 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Request example (call again)# Requires dashscope 2.0.1 or later
import os
import dashscope
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Enter the actual application ID
prompt='Food recommendations',
memory_id='MEMORY_ID') # Enter the actual memory ID
print('%s\n' % (response.text)) # Handle text-only output
# 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaRequest example (generate memory content)// DashScope SDK version must be 2.17.0 or later
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with the actual application ID
.prompt("User dietary preference: noodles")
.memoryId("MEMORY_ID") // Replace with the actual memory ID
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText()); // Handle text-only output
}
public static void main(String[] args) {
try {
callWithMemory();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Request example (call again)// DashScope SDK version must be 2.17.0 or later
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with the actual application ID
.prompt("Food recommendations")
.memoryId("MEMORY_ID") // Replace with the actual memory ID
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText()); // Handle text-only output
}
public static void main(String[] args) {
try {
callWithMemory();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest example (generate memory content)curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "User dietary preference: noodles",
"memory_id": "MEMORY_ID"
},
"parameters": {},
"debug": {}
}'
Request example (call again)curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Food recommendations",
"memory_id": "MEMORY_ID"
},
"parameters": {},
"debug": {}
}'
Replace APP_ID with the actual application ID.
PHPRequest example (generating memory content)<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$memory_id = 'MEMORY_ID'; // Replace with the actual memory ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'User dietary preference: noodles',
'memory_id' => $memory_id
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Request example (calling again)<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$memory_id = 'MEMORY_ID'; // Replace with the actual memory ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'Food recommendations',
'memory_id' => $memory_id
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Node.jsInstall the required dependencies:npm install axios
Request example (generating memory content)const axios = require('axios');
async function callDashScope() {
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const memoryId = 'MEMORY_ID';// Replace with the actual memory ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "User dietary preference: noodles",
memory_id: memoryId
},
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();
Request example (calling again)const axios = require('axios');
async function callDashScope() {
//If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application ID
const memoryId = 'MEMORY_ID';// Replace with the actual memory ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Food recommendations",
memory_id: memoryId
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#Request example (generating memory content)using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID";// Replace with the actual application ID
string memoryId = "MEMORY_ID";//Replace with the actual memory ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""User dietary preference: noodles"",
""memory_id"":""{memoryId}""
}},
""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}");
}
}
}
}
Request example (calling again)using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID";// Replace with the actual application ID
string memoryId = "MEMORY_ID";//Replace with the actual memory ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Food recommendations"",
""memory_id"":""{memoryId}""
}},
""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}");
}
}
}
}
GoRequest example (generating memory content)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "User dietary preference: noodles",
"memory_id": "MEMORY_ID", // Replace with the actual memory ID
},
"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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Request example (calling again)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Food recommendations",
"memory_id": "MEMORY_ID", // Replace with the actual memory ID
},
"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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Upload filesWhen calling an agent application, specify session_file_ids /file_list to enable the file upload feature. For more information, see File Q&A. PythonRequest exampleimport os
import dashscope
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace APP_ID with the actual application ID
prompt='Based on the following file, recommend a phone under 3,000 yuan',
rag_options={
"session_file_ids": ["Session_File_ID1"], # Replace Session_File_ID1 with the actual temporary file ID, separated by commas
}
)
print('%s\n' % (response.text)) # Handle text-only output
# 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaRequest example// Recommended dashscope SDK version: 2.17.0 or later;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with the actual application ID
.prompt("Based on the following file, recommend a phone around 3,000 yuan")
.ragOptions(RagOptions.builder()
.sessionFileIds(Arrays.asList("Session_File_ID1", "Session_File_ID2")) // Replace with the specified temporary file IDs, separated by commas
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Handle text-only output
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlRequest examplecurl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Based on the following file, recommend a phone under 3,000 yuan"
},
"parameters": {
"rag_options" : {
"session_file_ids":["Session_File_ID1"]}
},
"debug": {}
}'
PHPRequest example<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
'prompt' => 'Based on the following file, recommend a phone under 3,000 yuan'
],
"parameters" => [
'rag_options' => [
'session_file_ids' => ['Session_File_ID1']//Replace with the specified temporary file IDs, separated by commas
]
]
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Node.jsInstall the required dependencies:npm install axios
Request exampleconst axios = require('axios');
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';//Replace with the actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Based on the following file, recommend a phone under 3,000 yuan"
},
parameters: {
rag_options:{
session_file_ids:['Session_File_ID1'] // Replace with the specified temporary file IDs, separated by 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();
C#Request exampleusing System.Text;
class Program
{
static async Task Main(string[] args)
{
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID";// Replace with the actual application ID
// Replace Session_File_ID1 with the specified temporary file ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Based on the following file, recommend a phone under 3,000 yuan""
}},
""parameters"": {{
""rag_options"" : {{
""session_file_ids"":[""Session_File_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}");
}
}
}
}
GoRequest examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Based on the following file, recommend a phone under 3,000 yuan",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"session_file_ids": []string{"Session_File_ID1"}, // Replace with the actual temporary file
},
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Visual understandingEnable the visual understanding feature by passing an image URL or Data URL (Base64-encoded) through the image_list parameter. Application configuration: The application must use an image and video understanding model. Related document: File Q&A. NoteBase64 encoding of local images is supported. After the image is encoded into a Base64 string, build a Data URL in the data:[MIME_type];base64,{base64_image} format and pass it in. MIME_type must match the image format. Common formats: PNG uses image/png, JPEG uses image/jpeg, and WebP uses image/webp. PythonURL request exampleimport os
import dashscope
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError
client = dashscope.Client(
# If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace APP_ID with the actual application ID
prompt='What is this',
image_list=['https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg'],
)
print('%s\n' % (response.text)) # Handle text-only output
# 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Base64 encoding exampleimport os
import base64
import dashscope
from dashscope.v2 import DashScopeError
client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))
# Encode the local image as a Base64 string
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Encode the local image
base64_image = encode_image("/path/to/your/image.jpeg") # Replace with the actual image path
# Build the Data URL (the MIME type must match the image format)
data_url = f"data:image/jpeg;base64,{base64_image}"
# Call the application API
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace APP_ID with the actual application ID
prompt='What is in this image?',
image_list=[data_url], # Use the Data URL
)
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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
JavaURL request example// Recommended dashscope SDK version: 2.19.0 or later;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with the actual application ID
.prompt("What is this?")
.images(Arrays.asList("https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// Handle text-only output
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Base64 encoding example// Recommended dashscope SDK version: 2.19.0 or later
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.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
public class Main {
// Encode the local image as a Base64 string
public static String encodeImage(String imagePath) throws IOException {
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
return Base64.getEncoder().encodeToString(imageBytes);
}
public static void appCall() throws NoApiKeyException, InputRequiredException, IOException {
// Encode the local image
String base64Image = encodeImage("/path/to/your/image.jpeg"); // Replace with the actual image path
// Build the Data URL (the MIME type must match the image format)
String dataUrl = "data:image/jpeg;base64," + base64Image;
ApplicationParam param = ApplicationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // Replace with the actual application ID
.prompt("What is in this image?")
.images(Arrays.asList(dataUrl)) // Use the Data URL
.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 | IOException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlURL request examplecurl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What is this",
"image_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"]
},
"debug": {}
}'
Base64 encoding example# Encode the local image as a Base64 string
base64_image=$(base64 -i /path/to/your/image.jpeg) # macOS/Linux
# Build the Data URL (the MIME type must match the image format)
data_url="data:image/jpeg;base64,${base64_image}"
# Call the application API
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data "{
\"input\": {
\"prompt\": \"What is in this image?\",
\"image_list\": [\"${data_url}\"]
},
\"debug\": {}
}"
PHPURL request example<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Build the request data
$data = [
"input" => [
"prompt" => "What is this",
"image_list" => ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
],
"debug" => [],
];
// Encode the data as JSON
$dataString = json_encode($data);
// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL handle
$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 whether the cURL request succeeded
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 handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process 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";}
}
?>
Base64 encoding example<?php
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID';
function encodeImage($imagePath) {
if (!file_exists($imagePath)) die("Error: Image file not found");
return base64_encode(file_get_contents($imagePath));
}
$base64Image = encodeImage("/path/to/your/image.jpeg");
$dataUrl = "data:image/jpeg;base64," . $base64Image;
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
$data = ["input" => ["prompt" => "What is in this image?", "image_list" => [$dataUrl]], "debug" => []];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $api_key]);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status_code == 200) {
$response_data = json_decode($response, true);
echo $response_data['output']['text'];
}
?>
Node.jsInstall the required dependencies:npm install axios
URL request exampleimport axios from 'axios';
async function callDashScope() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';//Replace with the actual application ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "What is this",
image_list: ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
},
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();
Base64 encoding exampleimport axios from 'axios';
import fs from 'fs';
async function callWithBase64() {
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';
const imageBuffer = fs.readFileSync('/path/to/your/image.jpeg');
const base64Image = imageBuffer.toString('base64');
const dataUrl = `data:image/jpeg;base64,${base64Image}`;
const response = await axios.post(
`https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`,
{ input: { prompt: "What is in this image?", image_list: [dataUrl] } },
{ headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }
);
console.log(response.data.output.text);
}
callWithBase64();
C#URL request exampleusing System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID";// Replace with the actual application ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""What is this"",
""image_list"": [""https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg""]
}},
""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}");
}
}
}
}
Base64 encoding exampleusing System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
var appId = "APP_ID";
byte[] imageBytes = File.ReadAllBytes("/path/to/your/image.jpeg");
var base64Image = Convert.ToBase64String(imageBytes);
var dataUrl = $"data:image/jpeg;base64,{base64Image}";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var json = $@"{{""input"": {{""prompt"": ""What is in this image?"", ""image_list"": [""{dataUrl}""]}}, ""debug"": {{}}}}";
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
GoURL request examplepackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create the request body
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "What is this",
"image_list": []string{"https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
},
"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 the 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 the request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send the 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 the response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Process the 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))
}
}
Base64 encoding examplepackage main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID"
imageData, _ := os.ReadFile("/path/to/your/image.jpeg")
base64Image := base64.StdEncoding.EncodeToString(imageData)
dataUrl := fmt.Sprintf("data:image/jpeg;base64,%s", base64Image)
requestBody := map[string]interface{}{
"input": map[string]interface{}{"prompt": "What is in this image?", "image_list": []string{dataUrl}},
}
jsonData, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId), bytes.NewBuffer(jsonData))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
|