リクエストボディ | リクエスト例シングルラウンド会話Pythonリクエスト例 import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = Application.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることはお勧めしません。API キーが漏洩するリスクを軽減するためです。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',# 実際のアプリケーション ID に置き換えてください
prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(response.output.text)
Javaリクエスト例 // 推奨される 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;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることはお勧めしません。API キーが漏洩するリスクを軽減するためです。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_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://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code」をご参照ください。");
}
System.exit(0);
}
}
HTTPCurlリクエスト例 curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "あなたは誰ですか?"
},
"parameters": {},
"debug": {}
}'
YOUR_APP_ID は実際のアプリケーション ID に置き換えてください。 PHPリクエスト例 <?php
// 環境変数が設定されていない場合は、次の行を API キー ($api_key="sk-xxx") に置き換えることができます。ただし、API キーの漏洩のリスクを軽減するために、本番環境で API キーをコードに直接ハードコードすることはお勧めしません。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// リクエストデータを作成する
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// データを JSON としてエンコードする
$dataString = json_encode($data);
// json_encode が成功したかどうかを確認する
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON エンコードがエラーで失敗しました: " . 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 エラー: " . 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 "レスポンスにテキストがありません。\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=不明なエラー\n";}
}
?>
Node.js依存関係: npm install axios
リクエスト例 const axios = require('axios');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることができます。ただし、API キーの漏洩のリスクを軽減するために、本番環境で API キーをコードに直接ハードコーディングすることはお勧めしません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えます
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#リクエスト例 using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えることができます。ただし、API キーの漏洩のリスクを軽減するために、本番環境では API キーをコードに直接ハードコーディングすることはお勧めしません。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 実際のアプリケーション ID に置き換えてください
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Goサンプルリクエスト package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることができます。ただし、API キーの漏洩のリスクを軽減するために、本番環境では API キーをコードに直接ハードコーディングすることはお勧めしません。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えます
if apiKey == "" {
fmt.Println("Please ensure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエスト本文を作成する
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 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 を渡して、複数ラウンドの会話を実装します。詳細については、「複数ラウンドの会話」をご参照ください。
現在、複数ラウンドの会話をサポートしているのは、[エージェントアプリケーション] と [ダイアログワークフローアプリケーション] のみです。 Pythonリクエスト例 import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
def call_with_session():
response = Application.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 実際のアプリケーション ID に置き換えてください
prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 実際のアプリケーション ID に置き換えてください
prompt='What skills do you have?',
session_id=response.output.session_id) # 前回の応答からの 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
# print('%s\n' % (response.usage))
if __name__ == '__main__':
call_with_session()
Javaリクエスト例 import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void callWithSession()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 環境変数が構成されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キーの漏洩のリスクを軽減するためにお勧めしません。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 実際のアプリケーション ID に置き換えてください
.appId("YOUR_APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("What skills do you have?");
result = application.call(param);
System.out.printf("%s\n, session_id: %s\n",
result.getOutput().getText(), result.getOutput().getSessionId());
}
public static void main(String[] args) {
try {
callWithSession();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlリクエスト例(ラウンド 1) curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
リクエスト例(ラウンド 2) curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What skills do you have?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHPリクエスト例(ラウンド 1) <?php
# 環境変数が設定されていない場合は、次の行を API キーに置き換えることができます: $api_key="sk-xxx"。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するためにお勧めしません。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// リクエストデータを作成する
$data = [
"input" => [
'prompt' => 'Who are you?'
]
];
// データを JSON としてエンコードする
$dataString = json_encode($data);
// json_encode が成功したかどうかを確認する
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON エンコードエラー: " . 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 エラー: " . 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 "レスポンスにテキストがありません。\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=不明なエラー\n";
}
}
?>
リクエスト例(ラウンド 2) <?php
# 環境変数が設定されていない場合は、次の行を API キーに置き換えることができます: $api_key="sk-xxx"。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するためにお勧めしません。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// リクエストデータを作成する
$data = [
"input" => [
'prompt' => 'What skills do you have?',
// 前回の会話から返された session_id に置き換えてください
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// データを JSON としてエンコードする
$dataString = json_encode($data);
// json_encode が成功したかどうかを確認する
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON エンコードエラー: " . 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 エラー: " . 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 "レスポンスにテキストがありません。\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=不明なエラー\n";
}
}
?>
Node.js依存関係: npm install axios
リクエスト例(ラウンド 1) const axios = require('axios');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えてください
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
リクエスト例(ラウンド 2) const axios = require('axios');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えてください
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
// session_id を前回の会話の実際の session_id に置き換えてください
const data = {
input: {
prompt: "What skills do you have?",
session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#リクエスト例(ラウンド 1) using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 環境変数が構成されていない場合は、次の行を apiKey="sk-xxx" に置き換えることができます。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キーの漏洩のリスクを軽減するためにお勧めしません。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY 環境変数が設定されていません。");
string appId = "YOUR_APP_ID"; // 実際のアプリケーション ID に置き換えてください
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("リクエスト成功:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"リクエスト失敗、ステータスコード: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"DashScope 呼び出しエラー: {ex.Message}");
}
}
}
}
リクエスト例(ラウンド 2) using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 環境変数が構成されていない場合は、次の行を apiKey="sk-xxx" に置き換えることができます。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キーの漏洩のリスクを軽減するためにお勧めしません。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY 環境変数が設定されていません。");
string appId = "YOUR_APP_ID"; // 実際のアプリケーション ID に置き換えてください
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""What skills do you have?"",
""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("リクエスト成功:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"リクエスト失敗、ステータスコード: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"DashScope 呼び出しエラー: {ex.Message}");
}
}
}
}
Goリクエスト例(ラウンド 1) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数が構成されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることができます。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キーの漏洩のリスクを軽減するためにお勧めしません。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("DASHSCOPE_API_KEY が設定されていることを確認してください。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエスト本文を作成する
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("JSON のマーシャリングに失敗しました: %v\n", err)
return
}
// HTTP POST リクエストを作成する
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("リクエストの作成に失敗しました: %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("リクエストの送信に失敗しました: %v\n", err)
return
}
defer resp.Body.Close()
// レスポンスを読み取る
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("レスポンスの読み取りに失敗しました: %v\n", err)
return
}
// レスポンスを処理する
if resp.StatusCode == http.StatusOK {
fmt.Println("リクエスト成功:")
fmt.Println(string(body))
} else {
fmt.Printf("リクエスト失敗、ステータスコード: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
リクエスト例(ラウンド 2) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数が構成されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることができます。ただし、本番環境で API キーをコードに直接ハードコードすることは、API キーの漏洩のリスクを軽減するためにお勧めしません。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("DASHSCOPE_API_KEY が設定されていることを確認してください。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエスト本文を作成する
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "What skills do you have?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // 前回の会話から返された実際の session_id に置き換えてください。
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("JSON のマーシャリングに失敗しました: %v\n", err)
return
}
// HTTP POST リクエストを作成する
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("リクエストの作成に失敗しました: %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("リクエストの送信に失敗しました: %v\n", err)
return
}
defer resp.Body.Close()
// レスポンスを読み取る
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("レスポンスの読み取りに失敗しました: %v\n", err)
return
}
// レスポンスを処理する
if resp.StatusCode == http.StatusOK {
fmt.Println("リクエスト成功:")
fmt.Println(string(body))
} else {
fmt.Printf("リクエスト失敗、ステータスコード: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
YOUR_APP_ID を実際のアプリケーション ID に置き換えます。ラウンド 2 では、session_id を、ラウンド 1 から返された session_id で置き換えます。 パラメーターの受け渡しPythonリクエスト例 import os
from http import HTTPStatus
# 推奨 dashscope SDK バージョン >= 1.14.0
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
biz_params = {
# エージェント アプリケーションのカスタム プラグイン入力パラメーターの受け渡し。your_plugin_code をカスタム プラグイン ID に置き換えます。
"user_defined_params": {
"your_plugin_code": {
"article_index": 2}}}
response = Application.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることは、API キー漏洩のリスクを軽減するために推奨されません。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='Dormitory convention content',
biz_params=biz_params)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # テキスト出力のみを処理します
# print('%s\n' % (response.usage))
Javaリクエスト例 import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
// エージェント アプリケーションのカスタム プラグイン入力パラメーターの受け渡し。{your_plugin_code} をカスタム プラグイン ID に置き換えます
"{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることは、API キー漏洩のリスクを軽減するために推奨されません。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("Dormitory convention content")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlリクエスト例 curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Dormitory convention content",
"biz_params":
{
"user_defined_params":
{
"{your_plugin_code}":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
YOUR_APP_ID を実際のアプリケーション ID に置き換えます。 PHPリクエスト例 <?php
# 環境変数が設定されていない場合は、Dashscope API キーに置き換えます: $api_key="sk-xxx"。ただし、本番環境では API キーをコードに直接ハードコーディングすることは、API キー漏洩のリスクを軽減するために推奨されません。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えます
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// {your_plugin_code} を実際のプラグイン ID に置き換えます
// リクエスト データを構築します
$data = [
"input" => [
'prompt' => 'Dormitory convention content',
'biz_params' => [
'user_defined_params' => [
'{your_plugin_code}' => [
'article_index' => 2
]
]
]
],
];
// データを JSON としてエンコードします
$dataString = json_encode($data);
// json_encode が成功したかどうかを確認します
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON エンコード エラー: " . 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 エラー: " . 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 "レスポンスにテキストがありません。\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=不明なエラー\n";}
}
?>
Node.js依存関係: npm install axios
リクエスト例 const axios = require('axios');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることは、API キー漏洩のリスクを軽減するために推奨されません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えます
const pluginCode = 'YOUR_PLUGIN_CODE';// 実際のプラグイン ID に置き換えます
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Dormitory convention content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index はカスタム プラグインの変数です。実際のプラグイン変数に置き換えます
'article_index': 3
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#リクエスト例 using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることは、API キー漏洩のリスクを軽減するために推奨されません。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えます
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("DASHSCOPE_API_KEY が設定されていることを確認してください。");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "{your_plugin_code}"; // {your_plugin_code} を実際のプラグイン ID に置き換えます
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Dormitory convention content"",
""biz_params"": {{
""user_defined_params"": {{
""{pluginCode}"": {{
""article_index"": 2
}}
}}
}}
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("リクエスト成功:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"リクエスト失敗、ステータスコード: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"DashScope 呼び出しエラー: {ex.Message}");
}
}
}
}
Goリクエスト例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることは、API キー漏洩のリスクを軽減するために推奨されません。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えます
pluginCode := "YOUR_PLUGIN_CODE" // 実際のプラグイン ID に置き換えます
if apiKey == "" {
fmt.Println("DASHSCOPE_API_KEY が設定されていることを確認してください。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエスト本文を作成します
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "Dormitory convention content",
"biz_params": map[string]interface{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 2,
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("JSON のマーシャリングに失敗しました: %v\n", err)
return
}
// HTTP POST リクエストを作成します
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("リクエストの作成に失敗しました: %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("リクエストの送信に失敗しました: %v\n", err)
return
}
defer resp.Body.Close()
// レスポンスを読み取ります
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("レスポンスの読み取りに失敗しました: %v\n", err)
return
}
// レスポンスを処理します
if resp.StatusCode == http.StatusOK {
fmt.Println("リクエスト成功:")
fmt.Println(string(body))
} else {
fmt.Printf("リクエスト失敗、ステータスコード: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
ストリーミング出力Pythonリクエスト例 import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
responses = Application.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='Who are you?',
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'Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') # テキストのみを出力するための処理
Javaリクエスト例 // 推奨 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;// ストリーミング出力
// ストリーミング出力結果のエージェントアプリケーション実装
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 実際のアプリケーション ID に置き換えます
.appId("YOUR_APP_ID")
.prompt("Who are you?")
// 増分出力
.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("Please refer to the documentation: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlリクエスト例 curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
YOUR_APP_ID を実際のアプリケーション ID に置き換えます。 PHPリクエスト例 <?php
// 環境変数が設定されていない場合は、次の行を $api_key="sk-xxx" に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えます
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// リクエストデータを作成
$data = [
"input" => [
'prompt' => 'Who are you?'],
"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";
}
?>
Node.js依存関係: npm install axios
リクエスト例 1. 完全なレスポンスを出力 const axios = require('axios');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 実際のアプリケーション ID に置き換えます
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Who are you?"
},
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();
パネルを展開してサンプルコードを表示します。 2. テキストフィールドのみを出力 const axios = require('axios');
const { Transform } = require('stream');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えます
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: { prompt: "Who are you?" },
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 イベント(2 つの改行)で分割
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 parsing error:', 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("Pipeline error:", err));
} else {
console.log("Request failed, status code:", response.status);
response.data.on('data', chunk => console.log(chunk.toString()));
}
} catch (error) {
console.error(`API call failed: ${error.message}`);
if (error.response) {
console.error(`Status code: ${error.response.status}`);
error.response.data.on('data', chunk => console.log(chunk.toString()));
}
}
}
callDashScope();
C#リクエスト例 using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY 環境変数が設定されていません。");
string appId = "YOUR_APP_ID"; // 実際のアプリケーション ID に置き換えます
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
string jsonContent = @"{
""input"": {
""prompt"": ""Who are you""
},
""parameters"": {""incremental_output"": true},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request successful:");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
{
string? line; // null 許容文字列として宣言
while ((line = await reader.ReadLineAsync()) != null)
{
if (line.StartsWith("data:"))
{
string data = line.Substring(5).Trim();
Console.WriteLine(data);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
}
}
}
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Goリクエスト例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するため、お勧めしません。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えます
if apiKey == "" {
fmt.Println("DASHSCOPE_API_KEY が設定されていることを確認してください。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成します。incremental_output はストリーミングレスポンスを有効にするかどうかを示します
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Who are you?",
},
"parameters": map[string]interface{}{
"incremental_output": true,
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("JSON のマーシャリングに失敗しました: %v\n", err)
return
}
// HTTP POST リクエストを作成します
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("リクエストの作成に失敗しました: %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("リクエストの送信に失敗しました: %v\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("リクエストはステータスコード %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("レスポンスの読み取りエラー: %v\n", err)
break
}
}
}
ナレッジベースを取得するPythonリクエスト例 import os
from http import HTTPStatus
# 推奨 dashscope SDK バージョン >= 1.20.11
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = Application.call(
# 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # アプリケーション ID に置き換えてください
prompt='3000 元以下の携帯電話を推奨してください',
rag_options={
"pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"], # 実際のナレッジベース 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'Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # テキスト出力のみを処理します
# print('%s\n' % (response.usage))
Javaリクエスト例 // 推奨 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.Collections;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // 実際のアプリケーション ID に置き換えてください
.prompt("3000 元前後の携帯電話を推奨してください")
.ragOptions(RagOptions.builder()
// 実際に指定されたナレッジベース ID に置き換えてください。複数ある場合はカンマで区切ります
.pipelineIds(List.of("PIPELINES_ID1", "PIPELINES_ID2"))
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// テキスト出力のみを処理します
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPCurlリクエスト例 curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Please recommend a mobile phone under 3000 yuan"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["YOUR_PIPELINE_ID1"]}
},
"debug": {}
}'
YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に置き換えてください。 PHPリクエスト例 <?php
# 環境変数が設定されていない場合は、次の行を API キーに置き換えることができます: $api_key="sk-xxx"。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// リクエストデータを作成する
$data = [
"input" => [
'prompt' => '3000 元以下のスマートフォンを推奨してください。'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // 指定されたナレッジベース ID に置き換えてください。複数の ID はカンマで区切ります
]
]
];
// データを JSON としてエンコードする
$dataString = json_encode($data);
// json_encode が成功したかどうかを確認する
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON エンコードエラー: " . 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 エラー: " . 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 "レスポンスにテキストがありません。\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=不明なエラー\n";
}
}
?>
Node.js依存関係: npm install axios
リクエスト例 const axios = require('axios');
async function callDashScope() {
// 環境変数が設定されていない場合は、次の行を apiKey='sk-xxx' に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';//実際のアプリケーション ID に置き換えてください
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "3000 元以下の携帯電話を推奨してください"
},
parameters: {
rag_options:{
pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_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();
C#リクエスト例 using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 環境変数が設定されていない場合は、次の行を apiKey="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えてください
// YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に置き換えてください
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("DASHSCOPE_API_KEY が設定されていることを確認してください。");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""3000 元以下の携帯電話を推奨してください""
}},
""parameters"": {{
""rag_options"" : {{
""pipeline_ids"":[""YOUR_PIPELINE_ID1""]
}}
}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"リクエストがステータスコードで失敗しました: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"DashScope の呼び出し中にエラーが発生しました: {ex.Message}");
}
}
}
}
Goリクエスト例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数が設定されていない場合は、次の行を apiKey := "sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("DASHSCOPE_API_KEY が設定されていることを確認してください。")
return
}
url := fmt.Sprintf("https://dashscope-intl.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{"YOUR_PIPELINE_ID1"}, // 指定されたナレッジベース ID に置き換えてください
},
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("JSON のマーシャリングに失敗しました: %v\n", err)
return
}
// HTTP POST リクエストを作成する
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("リクエストの作成に失敗しました: %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("リクエストの送信に失敗しました: %v\n", err)
return
}
defer resp.Body.Close()
// レスポンスを読み取る
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("レスポンスの読み取りに失敗しました: %v\n", err)
return
}
// レスポンスを処理する
if resp.StatusCode == http.StatusOK {
fmt.Println("リクエスト成功:")
fmt.Println(string(body))
} else {
fmt.Printf("リクエストがステータスコードで失敗しました: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
取得プロセスを表示する: 呼び出しを行う際に、コードに has_thoughts を追加し、True に設定します。取得プロセスは thoughts フィールドの output に返されます。 |