リクエストボディ app_idstring(必須) アプリケーション ID。 アプリケーション管理 ページのアプリケーションカードからアプリケーション ID を取得します。
Java SDK ではこれは appId です。HTTP で呼び出す場合、実際のアプリケーション ID を URL 内の APP_ID に置き換えてください。
promptstring(必須) アプリケーションが応答を生成するよう指示するユーザー入力。
HTTP で呼び出す場合、prompt を input オブジェクト内に配置します。
session_idstring (任意) 会話履歴識別子。 session_id を渡すと、リクエストは自動的にクラウドに保存されている会話履歴を引き継ぎます。この場合、prompt を渡す必要があります。
1 時間の非アクティブ状態で期限切れになります。
Java SDK ではこれは setSessionId です。HTTP で呼び出す場合、session_id を input オブジェクト内に配置します。
messagesarray(任意) モデルに渡される会話コンテキストで、時系列順に並べられます。 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 である必要があります。
メッセージタイプ システムメッセージobject (任意) モデルのロール、トーン、タスク目的、制約を設定するシステムメッセージ。通常、messages 配列の先頭に配置されます。 プロパティ contentstring(必須) モデルのロール、動作ガイドライン、応答スタイル、タスク制約を定義するシステム命令。 rolestring(必須) システムメッセージのロールで、固定値は system です。 ユーザーメッセージobject(必須) 質問、命令、コンテキストをモデルに渡すユーザーメッセージ。 プロパティ contentstring(必須) メッセージ本文。 rolestring(必須) ユーザーメッセージのロールで、固定値は user です。 アシスタントメッセージobject (任意) モデルの応答。通常、マルチターン対話でモデルにコンテキストとして再渡しされます。 プロパティ contentstring(必須) モデル応答のテキスト本文。 rolestring(必須) アシスタントメッセージのロールで、固定値は assistant です。 workspace string (任意) ビジネススペース識別子。関連ドキュメント: ワークスペース ID の取得。 サブワークスペース 内のアプリケーションを呼び出す場合にのみ、ワークスペース ID を渡す必要があります。
HTTP で呼び出す場合、X-DashScope-WorkSpace ヘッダーを指定します。
stream boolean (任意)デフォルト値は False ストリーミング出力を有効にします。 True に設定すると、読み取り体験が向上し、タイムアウトのリスクが軽減されます。
パラメーター値:
False (デフォルト): モデルは生成が完了した後にすべてのコンテンツを一度に返します。
True (推奨): モデルは生成と同時にコンテンツを出力し、新しいコンテンツを生成するたびにデータチャンクを返します。完全な応答を組み立てるには、これらのチャンクをリアルタイムで読み取る必要があります。
Java SDK でストリーミング出力を実装するには、streamCall インターフェイスを使用します。HTTP でストリーミング出力を実装するには、X-DashScope-SSE ヘッダーを enable に設定します。
incremental_output boolean (任意)デフォルト値は False ストリーミングモードで増分出力を有効にします。 True に設定すると、読み取り体験が向上します。
パラメーター値:
False (デフォルト): 各出力には、それまでに生成されたシーケンス全体が含まれます。最終出力が完全な結果です。
I
I like
I like apple
I like apple.
True (推奨): 増分出力。後続の出力には、以前に出力されたコンテンツは含まれません。完全な結果を得るには、これらのセグメントをリアルタイムで読み取る必要があります。
I
like
apple
.
Java SDK ではこれは incrementalOutput です。HTTP で呼び出す場合、incremental_output を parameters オブジェクト内に配置します。
flow_stream_mode string (任意)デフォルト値は full_thoughts ワークフローアプリケーション のストリーミング出力モード。 パラメーター値:
-
message_format (推奨):
指定されたノード(Output ノードまたは End ノード)の結果を、message フィールドに出力します。
重要コンソールアプリケーションで、対象ノードの Stream スイッチを有効にすると、ストリーミングモードで結果が返されます。無効の場合、ノードの最終結果が一度に返されます。
Java SDK ではこれは FlowStreamMode.MESSAGE_FORMAT です。
-
full_thoughts (デフォルト):
すべてのノードの結果を thoughts フィールドに出力します。
重要このモードを使用する場合、has_thoughts パラメーターも True に設定する必要があります。
Java SDK ではこれは FlowStreamMode.FULL_THOUGHTS です。
-
agent_format:
指定されたノード(LLM ノードまたは終了ノード)の結果を textフィールドに出力します。
コンソールアプリケーションで、対象ノードの Response スイッチを有効にすると、ストリーミングモードで結果が返されます。
重要並列ノードと共にこのモードを使用しないでください。コンテンツが混在する可能性があります。有効化されたノードが明確な実行順序を持つことを確認してください。
Java SDK ではこれは FlowStreamMode.AGENT_FORMAT です。
Python SDK バージョンは少なくとも 1.24.0、Java SDK バージョンは少なくとも 2.21.0 である必要があります。HTTP で呼び出す場合、flow_stream_mode を parameters オブジェクト内に配置します。
biz_paramsobject (任意) アプリケーションがカスタム変数、ノード、プラグインを使用する場合に、このフィールドを使用してパラメーターを渡します。
Java SDK ではこれは bizParams です。HTTP で呼び出す場合、biz_params を input オブジェクト内に配置します。
ワークフローアプリケーション の場合、開始ノードのカスタム変数を直接渡します。例: biz_params = {"city": "Hangzhou"}
エージェントアプリケーション の場合、プロンプト変数またはプラグイン変数を以下のフィールドを使用して渡します: プロパティ user_defined_params object (任意) カスタムプラグインパラメーター情報。 アプリケーション内に追加されたプラグインは重複できません。最大 10 個のプラグインが使用できます。 プロパティ tool_idstring (任意) プラグイン ID。プラグインカードから確認できます。 ${plugin_params}string (任意) 最も内側のオブジェクトには複数のキーと値のペアが含まれます。各キーと値のペアは、ユーザー定義パラメーター名とその指定値を表します。例: "article_index": 2
使用手順:
- 指定されたプラグインをアプリケーションに関連付け、公開 します。
- API 呼び出し時に、このパラメーターを通じてプラグイン情報を渡します。
複数のキーと値のペアを提供できます。各キーはプラグインの TOOL_ID で、値はそのプラグインに必要なパラメーターオブジェクトです。例: "user_defined_params": {
"<TOOL_ID>": {
"article_index": 2},
"<TOOL_ID>": {
"article_index": 8}
}
user_defined_tokens object (任意) カスタムプラグイン用のユーザー認証情報。 アプリケーション内に追加されたプラグインは重複できません。最大 10 個のプラグインが使用できます。 プロパティ tool_idstring (任意) プラグイン ID。プラグインカードから確認できます。<TOOL_ID> フィールドを通じて渡します。 user_token string (任意) このプラグインに必要なユーザー認証情報を渡します。例: DASHSCOPE_API_KEY の実際の値。 使用手順:
- 指定されたプラグインをアプリケーションに関連付け、公開 します。
- API 呼び出し時に、このパラメーターを通じてプラグインのユーザー認証情報を渡します。
複数のキーと値のペアを提供できます。各キーはプラグインの TOOL_ID で、値は user_token オブジェクトです。 has_thoughts boolean (任意)デフォルト値は False プラグイン呼び出しやナレッジ取得プロセスが thoughts フィールドに出力されるかどうかを制御します。 パラメーター値:
- True: 出力が含まれます。
- False (デフォルト): 出力が含まれません。
Java SDK ではこれは hasThoughts です。HTTP で呼び出す場合、has_thoughts を parameters オブジェクト内に配置します。
rag_options object (任意) 取得に関連するパラメーターを構成するために使用され、指定されたナレッジベースやドキュメントの取得などが含まれます。 注記エージェントアプリケーション のみがこのパラメーターをサポートします。
Java SDK ではこれは ragOptions です。HTTP で呼び出す場合、rag_optionsを parameters オブジェクト内に配置します。
プロパティ pipeline_ids array(必須) 1 つ以上のナレッジベース ID を含むリスト。最大 5 個。 指定されたナレッジベース内のすべてのドキュメントを取得します。 取得方法:
- ナレッジベース ページからナレッジベース ID を取得します。
- または CreateIndex API(非構造化ナレッジベースのみをサポート)を通じて取得します。この API は
Data.Id を返します。
Java SDK ではこれは pipelineIds です。
file_idsarray(任意) 1 つ以上の非構造化ドキュメント ID を含むリスト。最大 5 個。 指定されたナレッジベース内の非構造化ドキュメントを取得します。 ドキュメント ID を渡す場合、これらのドキュメントが属するナレッジベース ID も pipeline_ids フィールドに渡す必要があります。 取得方法:
Java SDK ではこれは fileIds です。
metadata_filterobject (任意) メタデータによって非構造化ドキュメントをフィルタリングするために使用します。1 つ以上のキーと値のペアを指定することで、指定されたナレッジベース内にこのメタデータを持つ非構造化ドキュメントを取得します。 前提条件: メタデータを渡す場合、このメタデータが属するナレッジベース ID も pipeline_ids フィールドに渡す必要があります。 確認方法: このオブジェクトは 1 つ以上のキーと値のペアで構成されます: 組み合わせロジック: 異なるキーは「AND」ロジックを使用します。例: "author": "John.Doe", "source": ["internal_wiki", "public_docs"] は、「John.Doe」が作成した AND 「internal_wiki」または「public_docs」のいずれかから取得されたドキュメントをフィルタリングすることを意味します。
Java SDK ではこれは metadataFilter です。
tags array (任意) 非構造化ドキュメント用の 1 つ以上のタグを含むリスト。 このタグを持つ非構造化ドキュメントを取得できます。 確認方法: | シングルターン対話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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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'See documentation: https://www.alibabacloud.com/help/zh/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") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlリクエスト例curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
APP_ID を実際のアプリケーション ID に置き換えてください。
PHPリクエスト例<?php
# 環境変数を設定していない場合は、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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";}
}
?>
Node.js必要な依存関係をインストール:npm install axios
リクエスト例const axios = require('axios');
async function callDashScope() {
// 環境変数を設定していない場合は、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = '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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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-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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成
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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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'See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# 環境変数を設定していない場合は、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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'See documentation: https://www.alibabacloud.com/help/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()
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") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 実際のアプリケーション ID に置き換えてください
.appId("APP_ID")
.prompt("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("What skills do you have?");
result = application.call(param);
System.out.printf("%s\n session_id: %s\n",
result.getOutput().getText(), result.getOutput().getSessionId());
}
public static void main(String[] args) {
try {
callWithSession();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlリクエスト例(前回の会話)curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {},
"debug": {}
}'
リクエスト例(次のターン)curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "What skills do you have?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHPリクエスト例(前回の会話)<?php
# 環境変数を設定していない場合は、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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 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";}
}
?>
Node.js必要な依存関係をインストール:npm install axios
サンプルリクエスト(前回の会話)const axios = require('axios');
async function callDashScope() {
// 環境変数を設定していない場合は、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = '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();
リクエスト例(次のターン)const axios = require('axios');
async function callDashScope() {
// 環境変数を設定していない場合は、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = '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#リクエスト例(最初のターン)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//環境変数を設定していない場合は、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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-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}");
}
}
}
}
リクエスト例(次のターン)using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//環境変数を設定していない場合は、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""What skills do you have?"",
""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Goリクエスト例(前回の会話)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数を設定していない場合は、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成
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))
}
}
リクエスト例(次のターン)package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数を設定していない場合は、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成
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("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 を使用してカスタムパラメーターを渡します。
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 = {
# エージェントアプリケーションのカスタムプラグイン入力パラメーターを渡します。<TOOL_ID> をカスタムプラグイン ID に置き換えてください。
"user_defined_params": {
"<TOOL_ID>": {
"article_index": 2}}}
response = Application.call(
# 環境変数を設定していない場合は、次の行を api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID',
prompt='Dormitory rules content',
biz_params=biz_params)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'See documentation: https://www.alibabacloud.com/help/zh/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 =
// エージェントアプリケーションのカスタムプラグイン入力パラメーターを渡します。<TOOL_ID> をカスタムプラグイン ID に置き換えてください。
"{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// 環境変数を設定していない場合は、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("Dormitory rules content")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlリクエスト例curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Dormitory rules content",
"biz_params":
{
"user_defined_params":
{
"<TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
APP_ID を実際のアプリケーション ID に置き換えてください。<TOOL_ID> をプラグイン ID に置き換えてください。
PHPリクエスト例<?php
# 環境変数を設定していない場合は、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//<TOOL_ID> を実際のプラグイン ID に置き換えてください
// リクエストデータを構築
$data = [
"input" => [
'prompt' => 'Dormitory rules content',
'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";}
}
?>
Node.js必要な依存関係をインストール:npm install axios
リクエスト例const axios = require('axios');
async function callDashScope() {
// 環境変数を設定していない場合は、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// 実際のアプリケーション ID に置き換えてください
const pluginCode = 'TOOL_ID';// 実際のプラグイン ID に置き換えてください
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Dormitory rules content",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index はカスタムプラグインの変数です。実際のプラグイン変数に置き換えてください。
'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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "TOOL_ID"; // TOOL_ID を実際のプラグイン ID に置き換えてください
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Dormitory rules content"",
""biz_params"": {{
""user_defined_params"": {{
""{pluginCode}"": {{
""article_index"": 2
}}
}}
}}
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Goリクエスト例package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数を設定していない場合は、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください
pluginCode := "TOOL_ID" // 実際のプラグイン ID に置き換えてください
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "Dormitory rules content",
"biz_params": map[string]interface{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 2,
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 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))
}
}
ストリーミング出力stream を使用してストリーミング出力を有効にします。
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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='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'See documentation: https://www.alibabacloud.com/help/zh/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") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 実際のアプリケーション ID に置き換えてください
.appId("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("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlリクエスト例curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "Who are you?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
APP_ID を実際のアプリケーション ID に置き換えてください。
PHPリクエスト例<?php
// 環境変数を設定していない場合は、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = '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' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = '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' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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: "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("Pipe error:", err));
} else {
console.log("Request failed, status code:", response.status);
response.data.on('data', chunk => console.log(chunk.toString()));
}
} catch (error) {
console.error(`API call failed: ${error.message}`);
if (error.response) {
console.error(`Status code: ${error.response.status}`);
error.response.data.on('data', chunk => console.log(chunk.toString()));
}
}
}
callDashScope();
C#リクエスト例using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//環境変数を設定していない場合は、次の行を apiKey="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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"": ""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; // nullable string として宣言
while ((line = await reader.ReadLineAsync()) != null)
{
if (line.StartsWith("data:"))
{
string data = line.Substring(5).Trim();
Console.WriteLine(data);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
}
}
}
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Goリクエスト例package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
// 環境変数を設定していない場合は、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成。ここで 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("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 を使用してナレッジベース取得を有効にします。 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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='APP_ID', # APP_ID をアプリケーション ID に置き換えてください
prompt='Please recommend a phone under 3000 yuan',
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'See documentation: https://www.alibabacloud.com/help/zh/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.Arrays;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 環境変数を設定していない場合は、次の行を .apiKey("sk-xxx") に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID") // 実際のアプリケーション ID に置き換えてください
.prompt("Please recommend a phone around 3000 yuan")
.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());// テキストのみを出力するように処理
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("See documentation: https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurlリクエスト例curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "Please recommend a phone under 3000 yuan"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["PIPELINE_ID1"]}
},
"debug": {}
}'
APP_ID を実際のアプリケーション ID に、PIPELINE_ID1 を指定されたナレッジベース ID に置き換えてください。
PHPリクエスト例<?php
# 環境変数を設定していない場合は、次の行を $api_key="sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 実際のアプリケーション ID に置き換えてください
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// リクエストデータを構築
$data = [
"input" => [
'prompt' => 'Please recommend a phone under 3000 yuan'
],
"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";}
}
?>
Node.js必要な依存関係をインストール:npm install axios
リクエスト例const axios = require('axios');
async function callDashScope() {
// 環境変数を設定していない場合は、次の行を apiKey='sk-xxx' に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';//実際のアプリケーション ID に置き換えてください
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "Please recommend a phone under 3000 yuan"
},
parameters: {
rag_options:{
pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2'] // 指定されたナレッジベース 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" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
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("Make sure DASHSCOPE_API_KEY is set.");
return;
}
string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""Please recommend a phone under 3000 yuan""
}},
""parameters"": {{
""rag_options"" : {{
""pipeline_ids"":[""PIPELINE_ID1""]
}}
}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Goリクエスト例package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 環境変数を設定していない場合は、次の行を apiKey := "sk-xxx" に置き換え、Model Studio API キーを使用してください。ただし、本番環境では API キーをコード内にハードコードしないでください。これにより、API キー漏洩のリスクを軽減できます。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // 実際のアプリケーション ID に置き換えてください
if apiKey == "" {
fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// リクエストボディを作成
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "Please recommend a phone under 3000 yuan",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"pipeline_ids": []string{"PIPELINE_ID1"}, // 指定されたナレッジベース 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 フィールドで返されます。 |