请求体 app_id string(必选) 应用标识。 可在应用管理 页面的应用卡片上获取应用 ID。
Java SDK中为 appId。 通过 HTTP 调用时,请将实际的应用 ID 放入 URL 中,替换APP_ID。
prompt string(必选) 用户的输入指令,用于指导应用生成回复。
通过 HTTP 调用时,请将 prompt 放入 input 对象中。
session_id string (可选)历史对话标识。 传入session_id时,请求将自动携带云端存储的对话历史。此时必须传递prompt。 该 ID 在连续 1 小时内无任何请求后将自动失效。
Java SDK 中为 setSessionId 。通过 HTTP 调用时,请将 session_id 放入 input 对象中。
messages array(可选)传递给大模型的上下文,按对话顺序排列。 当使用messages参数实现多轮对话时,无需传递prompt和 session_id。 若同时传入session_id和messages,则大模型优先使用messages中的内容,忽略session_id和prompt。
通过HTTP调用时,请将 messages 放入 input 对象中。
使用该参数,Python Dashscope SDK的版本至少应为1.20.14,Java Dashscope SDK的版本至少应为2.17.0。
System Messageobject(可选) 系统消息,用于设定大模型的角色、语气、任务目标或约束条件等。一般放在messages数组的第一位。
content string(必选) 系统指令,用于明确模型的角色、行为规范、回答风格和任务约束等。 role string(必选) 系统消息的角色,固定为system。
User Messageobject(必选) 用户消息,用于向模型传递问题、指令或上下文等。
content string(必选) 消息内容。
text string(必选) 输入的文本。
role string(必选) 用户消息的角色,固定为user。 Assistant Messageobject(可选) 模型的回复。通常用于在多轮对话中作为上下文回传给模型。
content string(必选) 模型回复的文本内容。 role string(必选) 助手消息的角色,固定为assistant。
workspace string (可选)业务空间标识。相关文档:获取Workspace ID 。 仅调用子业务空间 的应用时需传递workspace ID。
通过 HTTP 调用时,请指定Header中的 X-DashScope-WorkSpace 。
stream boolean(可选) 默认值为 False是否以流式输出方式回复。 推荐设置为True,可提升阅读体验并降低超时风险。 参数值:
False(默认):模型生成全部内容后一次性返回;
True(推荐):边生成边输出,每生成一部分内容即返回一个数据块(chunk)。需实时逐个读取这些块以拼接完整回复。
通过Java SDK实现流式输出请通过streamCall接口调用;通过HTTP实现流式输出请在Header中指定X-DashScope-SSE为enable。
incremental_output boolean(可选)默认值为 False在流式输出模式下是否开启增量输出。 推荐设置为True,可提升阅读体验。 参数值:
False(默认):每次输出当前已经生成的整个序列,最后一次输出为生成的完整结果。
I
I like
I like apple
I like apple.
True(推荐):增量输出,即后续输出内容不包含已输出的内容。需要实时地逐个读取这些片段以获得完整的结果。
Java SDK中为incrementalOutput *。*通过HTTP调用时,请将incremental_output 放入parameters 对象中。
flow_stream_mode string(可选)默认值为full_thoughts工作流应用 的流式输出模式。相关文档:流式输出 。参数值:
message_format_plus(推荐) :消息增强模式。
在workflow_message字段输出所有节点的执行过程和结果,覆盖所有节点类型。与message_format返回相同的数据结构,但支持全部节点类型的流式推送。
客户端处理规则:文本类节点(OUTPUT / END text 模式)的message.content为增量 delta,需追加拼接;JSON 类节点(LLM / Component / AgentGroup 等)的message.content为完整 JSON 快照,需整体替换。当node_is_completed=true时标记该节点执行完毕。
子画布节点推流 :循环节点和批处理节点的子画布内节点也会流式推送,通过响应字段parent_node_id标识所属父节点。
暂不支持嵌套子画布:循环/批处理节点的子画布内不能再放置循环或批处理节点。
Java SDK 中为FlowStreamMode.MESSAGE_FORMAT_PLUS。
message_format(推荐) :消息模式。
在message字段输出指定节点(流程输出 节点或结束 节点)的结果。
在控制台应用中开启目标节点的流式输出 开关,即可流式返回结果;未开启时,一次性返回该节点的最终结果。
Java SDK 中为FlowStreamMode.MESSAGE_FORMAT。
full_thoughts(默认):完整思考模式。
不推荐新业务使用 。建议改用message_format或message_format_plus。
在thoughts字段输出所有节点的结果。
使用此模式时,必须同时将 has_thoughts 参数设置为 True。
Java SDK 中为FlowStreamMode.FULL_THOUGHTS。
Python SDK 版本至少为1.24.0,Java SDK 版本至少为2.22.23。通过HTTP调用时,请将flow_stream_mode 放入parameters 对象中。
biz_params object (可选)应用通过自定义变量、节点或插件传递参数时,使用该字段进行传递。相关文档:调用智能体应用-传递自定义参数 ,调用工作流应用-传递自定义参数 。
Java SDK 中为 bizParams 。通过HTTP调用时,请将 biz_params 放入 input 对象中。
工作流应用 开始节点的自定义变量直接传递,示例:biz_params = { "city" : "杭州" }
智能体应用 通过以下字段传递提示词变量或插件变量参数:
user_prompt_params object (可选)表示自定义提示词变量参数信息。 一个应用内的变量名不可重复,且上限 10 个。 使用步骤:
在应用内配置自定义变量并在提示词中引用 ,然后发布 应用。
API调用通过此参数传递变量信息。
示例: biz_params = {
"user_prompt_params" : {
"date" : "2025年03月03日" ,
"city" : "杭州"
}
}
user_defined_params object (可选)表示自定义插件参数信息。 一个应用内添加的插件不可重复,且上限 10 个。
tool_id string (可选)插件 ID,可在插件卡片上获取。 ${plugin_params} string(可选)对象最内侧包含的多个键值对。每个键值对表示用户自定义的待传递参数名及其指定值。如: 使用步骤:
在应用内关联指定插件,并发布 应用。
API调用通过此参数传递插件信息。
可提供多个键值对,其中每个键为插件的 TOOL_ID,值为该插件所需的参数对象。示例: "user_defined_params": {
"<TOOL_ID>": {
"article_index": 2},
"<TOOL_ID>": {
"article_index": 8}
}
user_defined_tokens object(可选)表示自定义插件的用户级鉴权信息。 一个应用内添加的插件不可重复,且上限 10 个。
tool_id string (可选)插件 ID,可在插件卡片中获取。通过<TOOL_ID>字段传递。 user_token string (可选)传递该插件需要的用户鉴权信息,如实际DASHSCOPE_API_KEY的值。
使用步骤:
在应用内关联指定插件,并发布 应用。
API调用通过此参数传递插件用户级鉴权信息。
可提供多个键值对,其中每个键为插件的 TOOL_ID,值为user_token 对象。 memory_id string (可选)长期记忆体 ID,参阅CreateMemory 创建。相关文档:长期记忆 。
在应用中打开长期记忆 开关,并发布 应用。
通过指定 memory_id 调用应用时,系统依据用户偏好信息自动构建和保存长期记忆。
后续使用同一 memory_id 调用时,系统会恢复这些长期记忆,并与最新的用户消息合并提供给模型处理。
Java SDK 中为 memoryId 。通过 HTTP 调用时,请将 memory_id 放入input 对象中。
has_thoughts boolean (可选)默认值为 False是否输出插件调用、知识检索的过程,或已开启思考模式的模型思考过程,在thoughts字段中查看。 参数值:
Java SDK 中为 hasThoughts 。通过 HTTP 调用时,请将 has_thoughts 放入 parameters 对象中。
image_list array(可选)图片列表。支持图像 URL 和 Data URL(Base64 编码)。应用内需选择图像与视频理解 模型。 base64编码格式可构建为 Data URL :data:[MIME_type];base64,{base64_image}。详细说明和代码示例见本文档右侧视觉理解 章节。使用场景:
图片检索(智能体应用 ):根据上传的图片链接,检索包含图片链接的结构化知识库。
视觉理解:通过千问VL系列模型 的视觉理解能力,分析图像内容实现问答。
相关文档:上传文件(文档、图片、视频或音频) 。
Java SDK 中为 images 。通过 HTTP 调用时,请将 image_list 放入 input 对象中。
file_list array(可选)包含一个或多个文件 URL 的列表。 相关文档:上传文件(文档、图片、视频或音频) 。
Java SDK中为 files 。通过HTTP调用时,请将 file_list 放入 input 对象中。
Python Dashscope SDK 的版本至少应为1.24.7,Java Dashscope SDK的版本至少应为2.21.13。
rag_options object (可选)用于配置与检索相关的参数。包括但不限于对指定的知识库或文档进行检索。相关文档:检索知识库 。
Java SDK 中为 ragOptions 。通过HTTP调用时,请将 rag_options 放入 parameters 对象中。
pipeline_ids array(必选) 包含一个或多个知识库 ID 的列表。上限5个。 检索指定知识库内的所有文档。 获取方式:
Java SDK 中为pipelineIds 。
file_ids array(可选)包含一个或多个非结构化文档 ID 的列表。上限5个。 检索指定知识库内的非结构化文档。 传入文档 ID 时,必须同时在 pipeline_ids 字段中传入这些文档所属的知识库 ID。 获取方式:
Java SDK 中为 fileIds 。
metadata_filter object (可选)用于筛选非结构化文档的元数据。通过指定一个或多个键值对,检索指定知识库内具备该元数据的非结构化文档。 使用前提: 传入元数据时,必须同时在 pipeline_ids 字段中传入这些元数据所属的知识库 ID。 查看方式: 该对象由一个或多个键值对组成:
键 (Key):String 类型,代表元数据的名称。
值 (Value):
单一值匹配:值为一个 String,表示只检索该字段值完全等于此字符串的文档。
多值“或”匹配:值为一个 Array (数组) 或 List (列表),包含多个 String。这表示检索该字段值匹配数组中任意一个值的文档(逻辑为 OR)。
示例: "source": ["internal_wiki", "public_docs"]
组合逻辑: 不同键之间为“与”(AND) 逻辑。例如,"author": "John.Doe", "source": ["internal_wiki", "public_docs"] 表示筛选出作者是 "John.Doe" 并且来源是 "internal_wiki" 或 "public_docs" 的文档。
Java SDK 中为 metadataFilter 。
tags array (可选)包含一个或多个非结构化文档标签的列表。 检索具备该标签的非结构化文档。 查看方式: structured_filter object (可选)用于对结构化数据进行元数据过滤。通过指定一个或多个键值对,可以筛选出符合条件的文档切片。 查看方式: 该对象由一个或多个键值对组成:
每个键(列名)都必须有对应的值,不支持仅通过列名筛选。
键 (Key):必须是 String 类型,代表要筛选的元数据字段名(列名)。
值 (Value):
单一条件匹配:值为一个 String 或 Number,表示只检索该字段值完全匹配的文档。示例:"category": "公司新闻"。
多值“或”匹配:值为一个 Array 或 List,包含多个 String 或 Number。这表示检索该字段值匹配数组中任意一个值的文档(逻辑为 OR)。示例:"year": 2024, "department": ["技术部", "产品部"]。
组合逻辑: 不同键之间为“与”(AND) 逻辑。例如,"year": 2024, "department": ["技术部", "产品部"] 表示筛选出年份是 2024 并且 部门是 "技术部" 或 "产品部" 的文档切片。
Java SDK 中为 structuredFilter 。
session_file_ids array(可选)包含一个或多个文件 ID 的列表。上限 10 个。 在调用智能体应用 时传递文件 ID,系统将提取文件中的文字内容 ,作为大模型问答的内容依据。 相关文档:上传文件(文档、图片、视频或音频) 。 会话文件ID必须以“file_session_”开头,且文件状态为 FILE_IS_READY。否则调用失败。
Java SDK 中为sessionFileIds 。
Python Dashscope SDK 的版本至少应为1.20.14,Java Dashscope SDK 的版本至少应为2.17.0。
model_id string(可选)模型名称。 API 调用时,可通过此参数传递本次调用使用的模型名称。 优先级:当通过 API 传递的model_id与控制台配置不同时,以 API 参数值为准。
Java SDK 中为 modelId 。通过HTTP调用时,请将 model_id 放入 parameters 对象中。
Java Dashscope SDK 的版本至少应为2.19.3 。
enable_system_time boolean (可选)默认值为 True控制模型是否自动获取当前时间(北京时间)。 参数值:
True(默认):启用当前时间,模型可直接响应实时时间请求(如“今天日期”)。
False:禁用当前时间。需通过自定义变量手动传入时间。例如:
# 通过 user_prompt_params 传递自定义时间
biz_params = {
"user_prompt_params" : {
"date" : "2025年03月03日"
}
}
适用场景:
需自定义时间来源,不依赖当前时间。
避免因当前时间变化导致模型输出结果变动。
Java SDK 中为 enableSystemTime 。通过HTTP调用时,请将 enable_system_time 放入 parameters 对象中。
Java Dashscope SDK 的版本至少应为2.19.3 。
enable_web_search boolean (可选)默认值为 false模型在生成回复时是否使用互联网搜索结果进行参考。 参数值:
True:启用互联网搜索,模型会将搜索结果作为生成回复过程中的参考信息。
False(默认):关闭互联网搜索。
优先级:
若调用时未设置此参数,以应用内联网搜索
开关状态为准。
若调用时设置了enable_web_search,以 API 参数为准。
启用互联网搜索功能可能会增加 Token 的消耗。
Java SDK中为enableWebSearch 。通过HTTP调用时,请将 enable_web_search 放入 parameters 对象中。
Java Dashscope SDK的版本至少应为2.19.3 。
dialog_round integer (可选)携带的上下文轮数。 设置输入模型的最大历史对话轮数,轮数越多,对话相关性越强。 优先级:当通过 API 传递的dialog_round与控制台配置不同时,则以 API 参数值为准。
Java SDK中为dialogRound 。通过HTTP调用时,请将 dialog_round 放入 parameters 对象中。
Java Dashscope SDK的版本至少应为2.19.3 。
enable_thinking boolean (可选)默认值为 false此参数用于在深度思考模型 中切换思考模式和非思考模式。仅适用于智能体应用 。 工作流应用 不支持通过此参数动态控制思考模式,需要在各大模型节点中分别设置。
参数值:
False(默认):非思考模式。直接返回最终答案(text字段)。
True:启用思考模式。模型先输出思考过程,再返回最终答案。
优先级:
若调用时未设置此参数,以应用内模型的思考模式开关状态为准。
若调用时设置了enable_thinking,以 API 参数为准。
要获取思考过程的内容,必须同时将has_thoughts设为True,则:
思考过程:智能体应用 通过thought字段获取,工作流应用 通过reasoningContent字段获取。
最终答案: text字段获取。
开启enable_thinking有极小概率不会输出思考过程。
Java SDK中为enableThinking 。通过HTTP调用时,请将 enable_thinking 放入 parameters 对象中。
Java Dashscope SDK的版本至少应为2.20.0 。
请求示例 import os
from http import HTTPStatus
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 替换为实际的应用 ID
prompt = '你是谁?' )
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print (response.output.text)
请求示例 // 建议dashscope SDK的版本 >= 2.12.0
import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void appCall ()
throws ApiException , NoApiKeyException , InputRequiredException {
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" )
. prompt ( "你是谁?" )
. 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 ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例 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": "你是谁?"
},
"parameters": {},
"debug": {}
}'
APP_ID替换为实际的应用 ID。
请求示例 <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
需安装相关依赖: 请求示例 const axios = require ( 'axios' );
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "你是谁?"
},
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 ();
请求示例 using System ;
using System . Net . Http ;
using System . Text ;
using System . Threading . Tasks ;
class Program
{
static async Task Main ( string [] args )
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用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 "" : "" 你是谁? ""
},
"" 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 } " );
}
}
}
}
请求示例 package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "你是谁?" ,
},
"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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
通过session_id或messages启用多轮对话。相关文档:调用智能体应用-多轮对话 ,调用工作流应用-多轮对话 。 请求示例 import os
from http import HTTPStatus
from dashscope import Application
def call_with_session ():
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 替换为实际的应用 ID
prompt = '你是谁?' )
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
return response
responseNext = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 替换为实际的应用 ID
prompt = '你有什么技能?' ,
session_id = response.output.session_id) # 上一轮response的session_id
if responseNext.status_code != HTTPStatus. OK :
print ( f 'request_id= { responseNext.request_id } ' )
print ( f 'code= { responseNext.status_code } ' )
print ( f 'message= { responseNext.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n session_id= %s \n ' % (responseNext.output.text, responseNext.output.session_id))
# print('%s\n' % (response.usage))
if __name__ == '__main__' :
call_with_session()
请求示例 import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void callWithSession ()
throws ApiException , NoApiKeyException , InputRequiredException {
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
// 替换为实际的应用 ID
. appId ( "APP_ID" )
. prompt ( "你是谁?" )
. build ();
Application application = new Application ();
ApplicationResult result = application . call (param);
param . setSessionId ( result . getOutput (). getSessionId ());
param . setPrompt ( "你有什么技能?" );
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 ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例(上一轮对话) 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": "你是谁?"
},
"parameters": {},
"debug": {}
}'
请求示例(下一轮对话) 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": "你有什么技能?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
请求示例(上一轮对话) <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
请求示例(下一轮对话) <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '你有什么技能?' ,
// 替换为实际上一轮对话返回的session_id
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
需安装相关依赖: 请求示例(上一轮对话) const axios = require ( 'axios' );
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "你是谁?"
},
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 ();
请求示例(下一轮对话) const axios = require ( 'axios' );
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
// session_id替换为实际上一轮对话的session_id
const data = {
input: {
prompt: "你有什么技能?" ,
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 ();
请求示例(上一轮对话) using System ;
using System . Net . Http ;
using System . Text ;
using System . Threading . Tasks ;
class Program
{
static async Task Main ( string [] args )
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用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 "" : "" 你是谁? ""
},
"" 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 } " );
}
}
}
}
请求示例(下一轮对话) using System ;
using System . Net . Http ;
using System . Text ;
using System . Threading . Tasks ;
class Program
{
static async Task Main ( string [] args )
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用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 "" : "" 你有什么技能? "" ,
"" 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 } " );
}
}
}
}
请求示例(上一轮对话) package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "你是谁?" ,
},
"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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
请求示例(下一轮对话) package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "你有什么技能?" ,
"session_id" : "f7eea37f0c734c20998a021b688d6de2" , // 替换为实际上一轮对话的session_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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
APP_ID替换为实际的应用 ID。下一轮对话的输入参数session_id字段值替换为实际上一轮对话返回的session_id值。
通过biz_params传递自定义参数。相关文档:调用智能体应用-传递自定义参数 ,调用工作流应用-传递自定义参数 。 请求示例 import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.14.0
from dashscope import Application
biz_params = {
# 智能体应用的自定义插件输入参数传递,自定义的插件ID替换<TOOL_ID>
"user_defined_params" : {
"<TOOL_ID>" : {
"article_index" : 2 }}}
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' ,
prompt = '寝室公约内容' ,
biz_params = biz_params)
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text)) # 处理只输出文本text
# print('%s\n' % (response.usage))
请求示例 import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static void appCall () throws NoApiKeyException , InputRequiredException {
String bizParams =
// 智能体应用的自定义插件输入参数传递,自定义的插件ID替换<TOOL_ID>
"{ \" user_defined_params \" :{ \" <TOOL_ID> \" :{ \" article_index \" :2}}}" ;
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" )
. prompt ( "寝室公约内容" )
. 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 ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例 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": "寝室公约内容",
"biz_params":
{
"user_defined_params":
{
"<TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
APP_ID替换为实际的应用 ID。<TOOL_ID>替换为插件ID。
请求示例 <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
//<TOOL_ID>替换为实际的插件ID
// 构造请求数据
$data = [
"input" => [
'prompt' => '寝室公约内容' ,
'biz_params' => [
'user_defined_params' => [
'<TOOL_ID>' => [
'article_index' => 2
]
]
]
],
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
需安装相关依赖: 请求示例 const axios = require ( 'axios' );
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const pluginCode = 'TOOL_ID' ; // 替换为实际的插件ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "寝室公约内容" ,
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index为自定义插件的变量,替换为实际的插件变量
'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 ();
请求示例 using System . Text ;
class Program
{
static async Task Main ( string [] args )
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用ID
if ( string . IsNullOrEmpty ( apiKey ))
{
Console . WriteLine ( "请确保设置了 DASHSCOPE_API_KEY。" );
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" ; // TOOL_ID替换为实际的插件 ID
string jsonContent = $@"{{
"" input "" : {{
"" prompt "" : "" 寝室公约内容 "" ,
"" 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 } " );
}
}
}
}
请求示例 package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
pluginCode := "TOOL_ID" // 替换为实际的插件 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] interface {}{
"prompt" : "寝室公约内容" ,
"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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
应用发布新版本后,APP_ID 始终指向最新已发布版本。发布时正在进行的请求不会被中断,会按发布前的配置正常完成;发布完成后,通过同一 APP_ID 发起的新请求将使用新版本的配置(包括提示词 、模型、工具等)。 API 不支持通过参数指定调用历史版本。请求体仅包含input和parameters字段,不提供版本号或历史版本参数。 多轮对话的session_id在新版本发布后继续使用时,可能出现上下文理解偏差或工具调用异常,因为该会话的历史上下文基于发布前的配置产生。建议在发布重大变更前结束活跃的多轮对话,或在发布后使用新的session_id重新开始会话。 如需恢复发布前的配置,请在百炼控制台 的应用详情页 执行版本回滚:
单击版本管理 。
选中需要恢复的历史版本。
单击覆盖当前草稿 。
单击发布 ,使回滚生效。
为降低对线上调用的影响,建议在业务低峰期发布重大变更;如需同时对外提供多个版本的能力,可通过创建多个应用(使用不同的 APP_ID)实现版本管理。 通过stream实现流式输出。相关文档:调用智能体应用-流式输出 ,调用工作流应用-流式输出 。 请求示例 import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' ,
prompt = '你是谁?' ,
stream = True , # 流式输出
incremental_output = True ) # 增量输出
for response in responses:
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( f ' { response.output.text } \n ' ) # 处理只输出文本text
请求示例 // 建议dashscope SDK的版本 >= 2.15.0
import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable; // 流式输出
// 智能体应用调用实现流式输出结果
public class Main {
public static void streamCall () throws NoApiKeyException , InputRequiredException {
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
// 替换为实际的应用 ID
. appId ( "APP_ID" )
. prompt ( "你是谁?" )
// 增量输出
. incrementalOutput ( true )
. build ();
Application application = new Application ();
// .streamCall():流式输出内容
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 ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例 curl -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": "你是谁?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
APP_ID替换为实际的应用 ID。
请求示例 <? php
// 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?' ],
"parameters" => [
'incremental_output' => true ]]; // 增量输出
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
curl_setopt ( $ch , CURLOPT_CUSTOMREQUEST , "POST" );
curl_setopt ( $ch , CURLOPT_POSTFIELDS , $dataString );
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , false ); // 不返回传输的数据
curl_setopt ( $ch , CURLOPT_WRITEFUNCTION , function ( $ch , $string ) {
echo $string ; // 处理流式数据
return strlen ( $string );
});
curl_setopt ( $ch , CURLOPT_HTTPHEADER , [
'Content-Type: application/json' ,
'Authorization: Bearer ' . $api_key ,
'X-DashScope-SSE: enable' // 流式输出
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
if ( $status_code != 200 ) {
echo "HTTP Status Code: $status_code \n " ;
echo "Request Failed. \n " ;
}
?>
需安装相关依赖: 请求示例
const axios = require ( 'axios' );
async function callDashScope () {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "你是谁?"
},
parameters: {
'incremental_output' : true // 增量输出
},
debug: {}
};
try {
console . log ( "Sending request to DashScope API..." );
const response = await axios . post ( url , data , {
headers: {
'Authorization' : `Bearer ${ apiKey } ` ,
'Content-Type' : 'application/json' ,
'X-DashScope-SSE' : 'enable' // 流式输出
},
responseType: 'stream' // 用于处理流式响应
});
if ( response . status === 200 ) {
// 处理流式响应
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 ();
可展开折叠面板查看具体内容:
const axios = require ( 'axios' );
const { Transform } = require ( 'stream' );
async function callDashScope () {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: { prompt: "你是谁?" },
parameters: { incremental_output: true }, // 增量输出
debug: {}
};
try {
console . log ( "Sending request to DashScope API..." );
const response = await axios . post ( url , data , {
headers: {
'Authorization' : `Bearer ${ apiKey } ` ,
'Content-Type' : 'application/json' ,
'X-DashScope-SSE' : 'enable' // 流式输出
},
responseType: 'stream' // 用于处理流式响应
});
if ( response . status === 200 ) {
// // 处理流式响应 SSE协议解析转换流
const sseTransformer = new Transform ({
transform ( chunk , encoding , callback ) {
this . buffer += chunk . toString ();
// 按SSE事件分割(两个换行符)
const events = this . buffer . split ( / \n\n / );
this . buffer = events . pop () || '' ; // 保留未完成部分
events . forEach ( eventData => {
const lines = eventData . split ( ' \n ' );
let textContent = '' ;
// 解析事件内容
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解析错误:' , e . message );
}
}
});
if ( textContent ) {
// 添加换行符并推送
this . push ( textContent + ' \n ' );
}
});
callback ();
},
flush ( callback ) {
if ( this . buffer ) {
this . push ( this . buffer + ' \n ' );
}
callback ();
}
});
sseTransformer . buffer = '' ;
// 管道处理
response . data
. pipe ( sseTransformer )
. on ( 'data' , ( textWithNewline ) => {
process . stdout . write ( textWithNewline ); // 自动换行输出
})
. on ( 'end' , () => console . log ( "" ))
. on ( 'error' , err => console . error ( "管道错误:" , err ));
} else {
console . log ( "请求失败,状态码:" , response . status );
response . data . on ( 'data' , chunk => console . log ( chunk . toString ()));
}
} catch ( error ) {
console . error ( `API调用失败: ${ error . message } ` );
if ( error . response ) {
console . error ( `状态码: ${ error . response . status } ` );
error . response . data . on ( 'data' , chunk => console . log ( chunk . toString ()));
}
}
}
callDashScope ();
请求示例 using System . Net ;
using System . Text ;
class Program
{
static async Task Main ( string [] args )
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用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 "" : "" 你是谁 ""
},
"" 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 ; // 声明为可空字符串
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 } " );
}
}
}
}
请求示例 package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
" strings "
" time "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体,其中incremental_output为是否开启流式响应
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "你是谁?" ,
},
"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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头,其中X-DashScope-SSE设置为enable,表示开启流式响应
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
req . Header . Set ( "X-DashScope-SSE" , "enable" )
// 发送请求
client := & http . Client {}
resp , err := client . Do ( req )
if err != nil {
fmt . Printf ( "Failed to send request: %v \n " , err )
return
}
defer resp . Body . Close ()
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
}
// 处理流式响应
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
}
}
}
调用智能体应用 时,通过rag_options实现知识库检索。相关文档:检索知识库 。 请求示例 import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.20.11
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 应用ID替换APP_ID
prompt = '请帮我推荐一款3000元以下的手机' ,
rag_options = {
"pipeline_ids" : [ "PIPELINE_ID1" , "PIPELINE_ID2" ], # 替换为实际的知识库ID,逗号隔开多个
}
)
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text)) # 处理只输出文本text
# print('%s\n' % (response.usage))
请求示例 // 建议dashscope SDK 的版本 >= 2.16.8;
import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
public class Main {
public static void streamCall () throws NoApiKeyException , InputRequiredException {
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" ) // 替换为实际的应用ID
. prompt ( "请帮我推荐一款3000元左右的手机" )
. ragOptions ( RagOptions . builder ()
// 替换为实际指定的知识库ID,逗号隔开多个
. 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 ()); // 处理只输出文本text
}
public static void main ( String [] args ) {
try {
streamCall ();
} catch ( ApiException | NoApiKeyException | InputRequiredException e ) {
System . out . printf ( "Exception: %s" , e . getMessage ());
System . out . println ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例 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": "请帮我推荐一款3000元以下的手机"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["PIPELINE_ID1"]}
},
"debug": {}
}'
APP_ID替换为实际的应用 ID,PIPELINE_ID1替换为指定的知识库ID。
请求示例 <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '请帮我推荐一款3000元以下的手机'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => [ 'PIPELINE_ID1' , 'PIPELINE_ID2' ] //替换为指定的知识库ID,逗号隔开多个
]
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
需安装相关依赖: 请求示例 const axios = require ( 'axios' );
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; //替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "请帮我推荐一款3000元以下的手机"
},
parameters: {
rag_options: {
pipeline_ids: [ 'PIPELINE_ID1' , 'PIPELINE_ID2' ] // 替换为指定的知识库ID,多个请用逗号隔开
}
},
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 ();
请求示例 using System . Text ;
class Program
{
static async Task Main ( string [] args )
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用ID
// PIPELINE_ID1替换为指定的知识库ID
if ( string . IsNullOrEmpty ( apiKey ))
{
Console . WriteLine ( "请确保设置了 DASHSCOPE_API_KEY。" );
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 "" : "" 请帮我推荐一款3000元以下的手机 ""
}},
"" 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 } " );
}
}
}
}
请求示例 package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "请帮我推荐一款3000元以下的手机" ,
},
"parameters" : map [ string ] interface {}{
"rag_options" : map [ string ] interface {}{
"pipeline_ids" : [] string { "PIPELINE_ID1" }, // 替换为指定的知识库ID
},
},
"debug" : map [ string ] interface {}{},
}
jsonData , err := json . Marshal ( requestBody )
if err != nil {
fmt . Printf ( "Failed to marshal JSON: %v \n " , err )
return
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
查看检索过程信息: 调用时在代码中添加has_thoughts并设置为True,则检索的过程信息会在output的thoughts字段中返回。调用智能体应用 时,指定 memory_id 启用长期记忆。相关文档:长期记忆 。 请求示例(生成记忆体内容) # DashScope SDK版本不低于1.22.1
from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 请输入实际的应用 ID
prompt = '用户饮食偏好:面食' ,
memory_id = 'MEMORY_ID' ) # 请输入实际的记忆体 ID
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text)) # 处理只输出text
# print('%s\n' % (response.usage))
请求示例(再次调用) # DashScope SDK版本不低于1.22.1
from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 请输入实际的应用 ID
prompt = '美食推荐' ,
memory_id = 'MEMORY_ID' ) # 请输入实际的记忆体 ID
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text)) # 处理只输出text
# print('%s\n' % (response.usage))
请求示例(生成记忆体内容) // DashScope SDK版本不低于2.17.0
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 ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" ) // 替换为实际的应用 ID
. prompt ( "用户饮食偏好:面食" )
. memoryId ( "MEMORY_ID" ) // 替换为实际的记忆体 ID
. build ();
Application application = new Application ();
ApplicationResult result = application . call (param);
System . out . printf ( "%s \n " ,
result . getOutput (). getText ()); // 处理只输出文本text
}
public static void main ( String [] args ) {
try {
callWithMemory ();
} catch ( ApiException | NoApiKeyException | InputRequiredException e ) {
System . out . printf ( "Exception: %s" , e . getMessage ());
System . out . println ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例(再次调用) // DashScope SDK版本不低于2.17.0
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 ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" ) // 替换为实际的应用 ID
. prompt ( "美食推荐" )
. memoryId ( "MEMORY_ID" ) // 替换为实际的记忆体 ID
. build ();
Application application = new Application ();
ApplicationResult result = application . call (param);
System . out . printf ( "text: %s \n " ,
result . getOutput (). getText ()); // 处理只输出文本text
}
public static void main ( String [] args ) {
try {
callWithMemory ();
} catch ( ApiException | NoApiKeyException | InputRequiredException e ) {
System . out . printf ( "Exception: %s" , e . getMessage ());
System . out . println ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例(生成记忆体内容) 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": "用户饮食偏好:面食",
"memory_id": "MEMORY_ID"
},
"parameters": {},
"debug": {}
}'
请求示例(再次调用) 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": "美食推荐",
"memory_id": "MEMORY_ID"
},
"parameters": {},
"debug": {}
}'
APP_ID替换为实际的应用 ID。
请求示例(生成记忆体内容) <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$memory_id = 'MEMORY_ID' ; // 替换为实际的记忆体 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{ $application_id }/completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '用户饮食偏好:面食' ,
'memory_id' => $memory_id
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
请求示例(再次调用) <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$memory_id = 'MEMORY_ID' ; // 替换为实际的记忆体 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{ $application_id }/completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '美食推荐' ,
'memory_id' => $memory_id
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
需安装相关依赖: 请求示例(生成记忆体内容) const axios = require ( 'axios' );
async function callDashScope () {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const memoryId = 'MEMORY_ID' ; // 替换为实际的memory_id
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "用户饮食偏好:面食" ,
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 ();
请求示例(再次调用) const axios = require ( 'axios' );
async function callDashScope () {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; // 替换为实际的应用 ID
const memoryId = 'MEMORY_ID' ; // 替换为实际的memory_id
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "美食推荐" ,
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 ();
请求示例(生成记忆体内容) using System . Text ;
class Program
{
static async Task Main ( string [] args )
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用ID
string memoryId = "MEMORY_ID" ; //替换为实际的memory_id
if ( string . IsNullOrEmpty ( apiKey ))
{
Console . WriteLine ( "请确保设置了 DASHSCOPE_API_KEY。" );
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 "" : "" 用户饮食偏好:面食 "" ,
"" 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 } " );
}
}
}
}
请求示例(再次调用) using System . Text ;
class Program
{
static async Task Main ( string [] args )
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用ID
string memoryId = "MEMORY_ID" ; //替换为实际的memory_id
if ( string . IsNullOrEmpty ( apiKey ))
{
Console . WriteLine ( "请确保设置了 DASHSCOPE_API_KEY。" );
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 "" : "" 美食推荐 "" ,
"" 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 } " );
}
}
}
}
请求示例(生成记忆体内容) package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "用户饮食偏好:面食" ,
"memory_id" : "MEMORY_ID" , // 替换为实际的记忆体 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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
请求示例(再次调用) package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "美食推荐" ,
"memory_id" : "MEMORY_ID" , // 替换为实际的记忆体 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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
调用智能体应用 时,指定 session_file_ids /file_list启用上传文件功能。相关文档:文件问答 。 请求示例 import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.20.14
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 应用ID替换APP_ID
prompt = '请根据以下文件帮我推荐一款3000元以下的手机' ,
rag_options = {
"session_file_ids" : [ "Session_File_ID1" ], # Session_File_ID1 替换为实际的临时文件ID,逗号隔开多个
}
)
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text)) # 处理只输出文本text
# print('%s\n' % (response.usage))
请求示例 // 建议dashscope SDK 的版本 >= 2.17.0;
import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
public class Main {
public static void appCall () throws NoApiKeyException , InputRequiredException {
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" ) // 替换为实际的应用ID
. prompt ( "请根据以下文件帮我推荐一款3000元左右的手机" )
. ragOptions ( RagOptions . builder ()
. sessionFileIds ( Arrays . asList ( "Session_File_ID1" , "Session_File_ID2" )) // 替换为实际指定的临时文件 ID,逗号隔开多个
. build ())
. build ();
Application application = new Application ();
ApplicationResult result = application . call (param);
System . out . printf ( "%s \n " ,
result . getOutput (). getText ()); // 处理只输出文本text
}
public static void main ( String [] args ) {
try {
appCall ();
} catch ( ApiException | NoApiKeyException | InputRequiredException e ) {
System . out . printf ( "Exception: %s" , e . getMessage ());
System . out . println ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
请求示例 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": "请根据以下文件帮我推荐一款3000元以下的手机"
},
"parameters": {
"rag_options" : {
"session_file_ids":["Session_File_ID1"]}
},
"debug": {}
}'
请求示例 <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
'prompt' => '请根据以下文件帮我推荐一款3000元以下的手机'
],
"parameters" => [
'rag_options' => [
'session_file_ids' => [ 'Session_File_ID1' ] //替换为指定的临时文件ID,逗号隔开多个
]
]
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 " ;}
}
?>
需安装相关依赖: 请求示例 const axios = require ( 'axios' );
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; //替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "请根据以下文件帮我推荐一款3000元以下的手机"
},
parameters: {
rag_options: {
session_file_ids: [ 'Session_File_ID1' ] // 替换为指定的临时文件 ID,多个请用逗号隔开
}
},
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 ();
请求示例 using System . Text ;
class Program
{
static async Task Main ( string [] args )
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用ID
// Session_File_ID1替换为指定的临时文件ID
if ( string . IsNullOrEmpty ( apiKey ))
{
Console . WriteLine ( "请确保设置了 DASHSCOPE_API_KEY。" );
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 "" : "" 请根据以下文件帮我推荐一款3000元以下的手机 ""
}},
"" 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 } " );
}
}
}
}
请求示例 package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] string {
"prompt" : "请根据以下文件帮我推荐一款3000元以下的手机" ,
},
"parameters" : map [ string ] interface {}{
"rag_options" : map [ string ] interface {}{
"session_file_ids" : [] string { "Session_File_ID1" }, // 替换为实际的临时文件
},
},
"debug" : map [ string ] interface {}{},
}
jsonData , err := json . Marshal ( requestBody )
if err != nil {
fmt . Printf ( "Failed to marshal JSON: %v \n " , err )
return
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 ))
}
}
通过 image_list 参数传入图像 URL 或 Data URL(Base64 编码)启用视觉理解功能。 应用配置: 应用内需使用图像与视频理解 模型。相关文档:文件问答 。支持使用 Base64 编码本地图像。将图像编码为 Base64 字符串后,按data:[MIME_type];base64,{base64_image}格式构建 Data URL 传入。MIME_type必须与图像格式匹配。常见格式:PNG 使用 image/png,JPEG 使用 image/jpeg,WebP 使用 image/webp。
URL请求示例 import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.20.14
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 应用ID替换APP_ID
prompt = '这是什么' ,
image_list = [ 'https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg' ],
)
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text)) # 处理只输出文本text
# print('%s\n' % (response.usage))
Base64 编码示例 import os
import base64
from http import HTTPStatus
from dashscope import Application
# 将本地图像编码为 Base64 字符串
def encode_image ( image_path ):
with open (image_path, "rb" ) as image_file:
return base64.b64encode(image_file.read()).decode( "utf-8" )
# 编码本地图像
base64_image = encode_image( "/path/to/your/image.jpeg" ) # 替换为实际图像路径
# 构建 Data URL(注意:MIME type 需与图像格式匹配)
data_url = f "data:image/jpeg;base64, { base64_image } "
# 调用应用 API
response = Application.call(
api_key = os.getenv( "DASHSCOPE_API_KEY" ),
app_id = 'APP_ID' , # 应用ID替换APP_ID
prompt = '这张图片里有什么?' ,
image_list = [data_url], # 使用 Data URL
)
if response.status_code != HTTPStatus. OK :
print ( f 'request_id= { response.request_id } ' )
print ( f 'code= { response.status_code } ' )
print ( f 'message= { response.message } ' )
print ( f '请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code' )
else :
print ( ' %s \n ' % (response.output.text))
URL请求示例 // 建议dashscope SDK 的版本 >= 2.19.0;
import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
public class Main {
public static void appCall () throws NoApiKeyException , InputRequiredException {
ApplicationParam param = ApplicationParam . builder ()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" ) // 替换为实际的应用ID
. prompt ( "这是什么?" )
. 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 ()); // 处理只输出文本text
}
public static void main ( String [] args ) {
try {
appCall ();
} catch ( ApiException | NoApiKeyException | InputRequiredException e ) {
System . out . printf ( "Exception: %s" , e . getMessage ());
System . out . println ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
Base64 编码示例 // 建议dashscope SDK 的版本 >= 2.19.0
import com.alibaba.dashscope.app. * ;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
public class Main {
// 将本地图像编码为 Base64 字符串
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 {
// 编码本地图像
String base64Image = encodeImage ( "/path/to/your/image.jpeg" ); // 替换为实际图像路径
// 构建 Data URL(注意:MIME type 需与图像格式匹配)
String dataUrl = "data:image/jpeg;base64," + base64Image;
ApplicationParam param = ApplicationParam . builder ()
. apiKey ( System . getenv ( "DASHSCOPE_API_KEY" ))
. appId ( "APP_ID" ) // 替换为实际的应用ID
. prompt ( "这张图片里有什么?" )
. images ( Arrays . asList (dataUrl)) // 使用 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 ( "请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code" );
}
System . exit ( 0 );
}
}
URL请求示例 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": "这是什么",
"image_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"]
},
"debug": {}
}'
Base64 编码示例 # 将本地图像编码为 Base64 字符串
base64_image = $( base64 -i /path/to/your/image.jpeg ) # macOS/Linux
# 构建 Data URL(注意:MIME type 需与图像格式匹配)
data_url = "data:image/jpeg;base64,${ base64_image }"
# 调用应用 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 \" : \" 这张图片里有什么? \" ,
\" image_list \" : [ \" ${ data_url } \" ]
},
\" debug \" : {}
}"
URL请求示例 <? php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv ( "DASHSCOPE_API_KEY" );
$application_id = 'APP_ID' ; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/ $application_id /completion" ;
// 构造请求数据
$data = [
"input" => [
"prompt" => "这是什么" ,
"image_list" => [ "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg" ],
],
"debug" => [],
];
// 将数据编码为 JSON
$dataString = json_encode ( $data );
// 检查 json_encode 是否成功
if ( json_last_error () !== JSON_ERROR_NONE ) {
die ( "JSON encoding failed with error: " . json_last_error_msg ());
}
// 初始化 cURL 对话
$ch = curl_init ( $url );
// 设置 cURL 选项
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
]);
// 执行请求
$response = curl_exec ( $ch );
// 检查 cURL 执行是否成功
if ( $response === false ) {
die ( "cURL Error: " . curl_error ( $ch ));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE );
// 关闭 cURL 对话
curl_close ( $ch );
// 解码响应数据
$response_data = json_decode ( $response , true );
// 处理响应
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 编码示例 <? 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" => "这张图片里有什么?" , "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' ];
}
?>
需安装相关依赖: URL请求示例 import axios from 'axios' ;
async function callDashScope () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process . env . DASHSCOPE_API_KEY ;
const appId = 'APP_ID' ; //替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/ ${ appId } /completion` ;
const data = {
input: {
prompt: "这是什么" ,
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 编码示例 import 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: "这张图片里有什么?" , image_list: [ dataUrl ] } },
{ headers: { 'Authorization' : `Bearer ${ apiKey } ` , 'Content-Type' : 'application/json' } }
);
console . log ( response . data . output . text );
}
callWithBase64 ();
URL请求示例 using System ;
using System . Net . Http ;
using System . Text ;
using System . Threading . Tasks ;
class Program
{
static async Task Main ( string [] args )
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment . GetEnvironmentVariable ( "DASHSCOPE_API_KEY" ) ?? throw new InvalidOperationException ( "DASHSCOPE_API_KEY environment variable is not set." );
string appId = "APP_ID" ; // 替换为实际的应用ID
if ( string . IsNullOrEmpty ( apiKey ))
{
Console . WriteLine ( "请确保设置了 DASHSCOPE_API_KEY。" );
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 "" : "" 这是什么 "" ,
"" 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 编码示例 using 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 "" : "" 这张图片里有什么? "" , "" 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 ());
}
}
URL请求示例 package main
import (
" bytes "
" encoding/json "
" fmt "
" io "
" net/http "
" os "
)
func main () {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os . Getenv ( "DASHSCOPE_API_KEY" )
appId := "APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt . Println ( "请确保设置了DASHSCOPE_API_KEY。" )
return
}
url := fmt . Sprintf ( "https://dashscope.aliyuncs.com/api/v1/apps/ %s /completion" , appId )
// 创建请求体
requestBody := map [ string ] interface {}{
"input" : map [ string ] interface {}{
"prompt" : "这是什么" ,
"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
}
// 创建 HTTP POST 请求
req , err := http . NewRequest ( "POST" , url , bytes . NewBuffer ( jsonData ))
if err != nil {
fmt . Printf ( "Failed to create request: %v \n " , err )
return
}
// 设置请求头
req . Header . Set ( "Authorization" , "Bearer " + apiKey )
req . Header . Set ( "Content-Type" , "application/json" )
// 发送请求
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 ()
// 读取响应
body , err := io . ReadAll ( resp . Body )
if err != nil {
fmt . Printf ( "Failed to read response: %v \n " , err )
return
}
// 处理响应
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 编码示例 package 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" : "这张图片里有什么?" , "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 ))
}