DashScope SDK または HTTP を使用して、Model Studio のエージェント、ワークフロー、またはエージェントオーケストレーションアプリケーションを業務システムに統合できます。
前提条件
Model Studio アプリケーションを作成し、[マイアプリケーション] ページでアプリケーション ID(APP_ID)を取得していること。
DashScope SDK または HTTP インターフェースを使用して、Model Studio アプリケーションを呼び出すことができます。使用する前に環境を準備してください。
どの呼び出し方法を使用する場合でも、API キーを環境変数として構成することをお勧めします。DashScope SDK を使用する場合は、DashScope SDK をインストールする必要もあります。
使用方法
単一ラウンドの会話
DashScope SDK または HTTP メソッドで単一ラウンドの会話を実装するためのサンプルコード。
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)サンプルレスポンス
I am a large language model developed by Alibaba Cloud, named Qwen. I am designed to help users generate various types of text, such as articles, stories, poems, stories, etc., and can be adjusted and optimized according to different scenarios and needs. In addition, I can also answer various questions, provide information and explanations, and assist in learning and research. If you have any needs, please feel free to ask me questions at any time!Java
サンプルリクエスト
// 推奨される 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("Who are you?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}サンプルレスポンス
text: I am a large language model developed by Alibaba Cloud, named Qwen.HTTP
curl
サンプルリクエスト
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": {}
}' YOUR_APP_ID を実際のアプリケーション ID に置き換えてください。
サンプルレスポンス
{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am an AI assistant who can answer questions, create text, express opinions, and even write code. If you have any questions or need assistance, please don't hesitate to let me know, and I will do my best to provide you with the help you need."},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}% PHP
サンプルリクエスト
<?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";}
}
?>サンプルレスポンス
I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen.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();サンプルレスポンス
I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen.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("リクエスト成功:");
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}");
}
}
}
}サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "c274e14a58d9492f9baeffdc003a97c5",
"text": "I am a super-large-scale language model developed by Alibaba Cloud, and my name is Qwen. I am designed to assist users in generating various types of text, such as articles, stories, poems, etc., and can adapt and innovate according to different scenarios and needs. Additionally, I am capable of answering a wide range of questions, providing information and explanations, and helping users solve problems and acquire knowledge. If you have any questions or need assistance, please feel free to let me know anytime!"
},
"usage": {
"models": [
{
"output_tokens": 79,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "5c4b86b1-cd2d-9847-8d00-3fba8f187bc6"
}Go
サンプルリクエスト
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))
}
}
サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "6105c965c31b40958a43dc93c28c7a59",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}複数ラウンドの会話
複数ラウンドの会話では、LLM は会話履歴を参照できるため、日常のコミュニケーションシナリオにさらに近くなります。
現在、エージェントアプリケーションとダイアログワークフローアプリケーションのみが複数ラウンドの会話をサポートしています。
session_idを渡すと、リクエストはクラウドに保存されている会話履歴を自動的に伝達します。session_idを渡す場合は、promptが必須です。messages配列を維持することもできます。会話履歴の各ラウンドと新しい指示をmessages配列に追加します。次に、messagesを介して履歴を渡します。messagesを渡す場合は、promptはオプションです。両方が渡された場合、promptは補足情報としてmessagesの末尾に追加されます。
session_idとmessagesの両方が渡された場合、messagesが優先的に使用されます。
クラウドストレージ (session_id)
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()サンプルレスポンス
I have multiple skills and can assist you with various tasks. Here are some of my main skills:
1. **Information retrieval**: Providing weather, news, historical facts, scientific knowledge, and various other information.
2. **Language processing**: Translating text, correcting grammar errors, generating articles and stories.
3. **Technical problem solving**: Answering programming questions, software usage, technical troubleshooting, etc.
4. **Educational assistance**: Helping with questions in subjects like mathematics, physics, chemistry, etc.
5. **Life advice**: Providing advice on health, diet, travel, shopping, etc.
6. **Entertainment interaction**: Telling jokes, playing word games, engaging in simple chat interactions.
7. **Schedule management**: Reminding important dates, arranging schedules, setting reminders.
8. **Data analysis**: Explaining data charts, providing data analysis suggestions.
9. **Emotional support**: Listening to your feelings, providing comfort and support.
If you have specific needs or questions, you can tell me directly, and I'll do my best to help you!
session_id=98ceb3ca0c4e4b05a20a00f913050b42Java
サンプルリクエスト
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);
}
}サンプルレスポンス
私は複数のスキルを持っており、さまざまな種類の支援を提供できます。主なスキルをいくつかご紹介します。
1. **多言語理解と生成**: 中国語と英語を含む複数の言語でテキストを理解し、生成できます。
2. **情報検索と統合**: あなたの質問に基づいて関連情報を検索し、整理して要約できます。
3. **ライティング支援**: 記事、レポート、創作など、ライティングのサポートを提供できます。
4. **プログラミング支援**: プログラマー向けに、プログラミング関連の質問に答えたり、コード例を提供したりできます。
5. **教育指導**: 学習過程で困難に遭遇した場合、数学から歴史まで複数の分野を網羅したアシスタントとして支援を提供できます。
6. **生活アドバイス**: 健康的な食事、旅行計画などに関連する問題についてもアドバイスを提供できます。
7. **感情的なコミュニケーション**: AI ですが、温かく、サポート的な方法であなたとコミュニケーションをとるよう努めます。
特定のニーズがある場合、または特定の側面について詳しく知りたい場合は、お気軽にお知らせください。
, session_id: f2e94a980a34424fa25be45a7048d77cHTTP
curl
サンプルリクエスト (ラウンド 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": {}
}' サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}サンプルリクエスト (ラウンド 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": {}
}' サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "As an AI assistant, I have multiple skills that can help you complete various tasks, including but not limited to:
1. **Knowledge queries**: I can help you find information in various fields such as science, history, culture, technology, etc.
2. **Language translation**: I can help you translate text in different languages, supporting translation between multiple languages.
3. **Text generation**: I can generate articles, stories, poems, press releases, and various other types of text.
4. **Question answering**: Whether it's academic questions, common knowledge, or technical problems, I can try to provide answers for you.
5. **Conversational exchange**: I can have natural and smooth conversations with you, providing emotional support or entertainment.
6. **Code writing and debugging**: I can help you write code and solve problems in programming.
7. **Data analysis**: I can help you analyze data, provide statistical results and visualization suggestions.
8. **Creative inspiration**: If you need creative inspiration, such as design, advertising copy, marketing strategies, etc., I can also provide help.
If you have any specific needs or questions, feel free to tell me anytime!"
},
"usage": {
"models": [
{
"output_tokens": 208,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}PHP
サンプルリクエスト (ラウンド 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";
}
}
?>
サンプルレスポンス
私は Alibaba Cloud の大規模言語モデルで、Qwen という名前です。
session_id=2e658bcb514f4d30ab7500b4766a8d43サンプルリクエスト (ラウンド 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";
}
}
?>
サンプルレスポンス
私は複数のスキルを持っており、以下を含みますが、これらに限定されません。
1. **多言語機能**: 複数の言語でテキストコンテンツを理解し、生成できます。
2. **執筆と作成**: 記事、ストーリー、詩、その他のクリエイティブコンテンツの執筆を支援します。
3. **知識 Q&A**: さまざまな分野の一般的な質問や専門的な質問に答えます。
4. **コードの記述と理解**: 簡単なプログラムコードを記述し、コードの説明やデバッグを支援できます。
5. **論理的推論**: 論理的思考を必要とする問題やパズルを解決します。
6. **感情的サポート**: 前向きな心理的サポートと励ましを提供します。
7. **ゲームとエンターテイメント**: 語彙ゲームやその他の形式のインタラクティブなエンターテイメントアクティビティに参加します。
私の目標は、あなたの有能なアシスタントになり、必要なときに支援とサポートを提供することです。特定のニーズや試してみたい機能がある場合は、お気軽にお知らせください。
session_id=2e658bcb514f4d30ab7500b4766a8d43Node.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();サンプルレスポンス
私は Alibaba Cloud によって開発された人工知能アシスタント、Qwen です。さまざまな質問に答えたり、情報を提供したり、ユーザーと会話したりできます。何かお手伝いできることはありますか?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3サンプルリクエスト (ラウンド 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();サンプルレスポンス
さまざまなタスクや質問の処理に役立つさまざまなスキルがあります。主なスキル分野を次に示します。
1. **情報クエリと取得**: 特定の情報、データ、またはニュースを見つけるのに役立ちます。
2. **執筆と作成**: 記事、ストーリー、詩、レポートなどの作成など。
3. **言語翻訳**: さまざまな言語間の翻訳サービスを提供できます。
4. **教育指導**: 学術的な質問に答え、複雑な概念の理解を助けます。
5. **テクニカルサポート**: コンピューターの使用で発生した技術的な問題を解決します。
6. **生活アドバイス**: 健康、食事、旅行などの側面についてアドバイスを提供します。
7. **エンターテイメントインタラクション**: ジョークを言ったり、言葉遊びをしたり、その他のリラックスできるアクティビティをしたりします。
特定のニーズがある場合、または特定の側面について詳しく知りたい場合は、お知らせください。
session_id=fe4ce8b093bf46159ea9927a7b22f0d3C#
サンプルリクエスト (ラウンド 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 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("リクエスト成功:");
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}");
}
}
}
}サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}サンプルリクエスト (ラウンド 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 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"": ""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}");
}
}
}
}サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "I have multiple skills and can:
- Answer knowledge questions from a wide range of fields
- Provide learning resources and suggestions
- Assist with technical problems
- Communicate in multiple languages
- Help plan trips and activities
- Provide practical advice for daily life
If you have any specific needs or questions, feel free to let me know!"
},
"usage": {
"models": [
{
"output_tokens": 70,
"model_id": "qwen-plus",
"input_tokens": 123
}
]
},
"request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}Go
サンプルリクエスト (ラウンド 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))
}
}
サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer various questions, provide information, and engage in conversations with users. Is there anything I can help you with?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}サンプルリクエスト (ラウンド 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))
}
}
サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "I have multiple skills and can:
- Answer various knowledge questions in fields such as science, history, culture, etc.
- Provide practical advice, such as travel tips, health tips, study methods, etc.
- Assist with text work, such as writing articles, editing documents, creating stories or poems.
- Perform multilingual translation, supporting translation between multiple languages.
- Have natural and smooth conversations with users, keeping them company, answering questions.
If you have any specific needs, feel free to let me know!"
},
"usage": {
"models": [
{
"output_tokens": 104,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}YOUR_APP_ID を実際のアプリケーション ID に置き換えてください。ラウンド 2 では、session_id をラウンド 1 から返された実際の session_id に置き換えてください。セルフマネジメント (messages)
Python
サンプルリクエスト
# dashscope SDK バージョンは >= 1.20.14 である必要があります
import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'},
{"role": "assistant","content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."},
{"role": "user","content": "What can you do?"}
]
response = Application.call(
# 環境変数が構成されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることはお勧めしません。API キーの漏洩のリスクを軽減するためです。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 実際のアプリケーション ID に置き換えてください
messages=messages)
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/error-code')
else:
print('%s\n' % (response.output.text))サンプルレスポンス
Qwen として、以下を含みますが、これらに限定されないさまざまなタスクを実行するお手伝いができます。
1. 質問への回答: 科学的知識、技術的な問題、常識など、正確な情報と回答を提供できます。
2. テキストの作成: ストーリー、詩、記事などを記述し、指定された条件に基づいてクリエイティブなコンテンツを生成します。
3. プログラミングアシスタント: プログラミング学習を支援し、コードロジックを説明し、プログラムエラーのデバッグなどを支援できます。
4. 言語翻訳: 複数の言語間の翻訳サービスをサポートします。
5. 提案の提供: 意思決定に直面したときにアドバイスや解決策を提供します。
6. 感情的なコミュニケーション: ユーザーとの会話に参加し、耳を傾け、前向きな反応とサポートを提供します。
つまり、私の目標は、仕事と生活の中であなたの有能なアシスタントになることです。特定のニーズがある場合は、お気軽にお知らせください。Java
サンプルリクエスト
// dashscope SDK バージョンは >= 2.17.0 である必要があります
import java.util.ArrayList;
import java.util.List;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
List messages = new ArrayList<>();
messages.add(Message.builder().role("system").content("You are a helpful assistant.").build());
messages.add(Message.builder().role("user").content("Who are you?").build());
messages.add(Message.builder().role("assistant").content("I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.").build());
messages.add(Message.builder().role("user").content("What can you do?").build());
ApplicationParam param = ApplicationParam.builder()
// 環境変数が構成されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることはお勧めしません。API キーの漏洩のリスクを軽減するためです。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.messages(messages)
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try{
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message: "+e.getMessage());
System.out.println("Refer to: https://www.alibabacloud.com/help/en/model-studio/error-code");
}
System.exit(0);
}
}サンプルレスポンス
text: 以下を含みますが、これらに限定されないさまざまなタスクを実行するお手伝いができます。
1. 質問への回答: 学術的な質問、常識、または専門分野の質問など、正確な回答を提供するために最善を尽くします。
2. テキストの作成: ストーリー、公式文書、メール、スクリプトなどを記述します。基本的な情報と要件を教えてください。
3. 表の処理: データの整理、表の生成または変更を支援できます。
4. コードの記述: 複数のプログラミング言語でのコードの記述と説明をサポートします。
5. 多言語翻訳: さまざまな言語間で翻訳できます。
6. シミュレートされた対話: さまざまな役割を演じて、ユーザーとシミュレートされた会話を行うことができます。
特定のニーズがある場合は、お気軽にお知らせください。HTTP
curl
サンプルリクエスト
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": {
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
},
{
"role": "assistant",
"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
},
{
"role": "user",
"content": "What can you do?"
}
]
},
"parameters": {},
"debug": {}
}' サンプルレスポンス
{"output":
{"finish_reason":"stop","session_id":"990ca89d89794826976d7499ad10cddb",
"text":"以下を含みますが、これらに限定されないさまざまなタスクを実行するお手伝いができます。\n\n1. 質問への回答: 学術的知識、実践的なヒント、常識の質問など、正確な回答を提供するために最善を尽くします。\n2. テキストの作成: ストーリー、公式文書、メール、スクリプトなどを記述します。具体的なニーズを教えていただければ、執筆のお手伝いができます。\n3. 意見の表明: 主観的な質問についても、私自身の見解を述べ、あなたと話し合うことができます。\n4. ゲームとエンターテイメント: 一緒に言葉遊びをしたり、ジョークを言ってリラックスしてもらったりできます。\n\nつまり、言語に関連することなら何でも、私に助けを求めることができます。"},
"usage":{"models":[{"output_tokens":126,"model_id":"qwen-max","input_tokens":86}]},"request_id":"3908c4a3-8d7a-9e51-81a5-0fc366582990"}% 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" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
],
[
"role" => "assistant",
"content" => "I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen."
],
[
"role" => "user",
"content" => "What can you do?"
]
]
]
];
// データを 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";
}
}
?>
サンプルレスポンス
次のようなさまざまなタスクを実行するお手伝いができます。
1. 質問への回答: 学術的な質問、実践的な知識、エンターテイメントのゴシップなど、正確な回答を提供するために最善を尽くします。
2. テキストの作成: ストーリー、公式文書、メールなどを記述します。
3. アドバイスの提供: 旅行の提案、学習方法、キャリアプランニングなどのガイダンスとアドバイス。
4. 会話への参加: チャット、感情の共有、興味深い議論を行うことができます。
何か助けが必要な場合は、お知らせください。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": {
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
},
{
"role": "assistant",
"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen."
},
{
"role": "user",
"content": "What can you do?"
}
]
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();サンプルレスポンス
以下を含みますが、これらに限定されないさまざまなタスクを実行するお手伝いができます。
1. 質問への回答: 学術的知識、実践的な情報、常識の質問など、正確な回答を提供するために最善を尽くします。
2. テキストの作成: ストーリー、公式文書、メール、スクリプトなどを記述します。十分な背景情報と要件を提供していただければ、執筆のお手伝いができます。
3. 提案の提供: 特定の決定についてアドバイスが必要な場合 (旅行先の選択、ギフトの選択、学習方法など)、説明に基づいて提案を提供することもできます。
4. 言語翻訳: 複数の言語間のテキスト翻訳をサポートします。
5. コードの記述と説明: プログラミング関連の質問については、簡単なプログラムの記述や複雑な概念の説明を支援できます。
6. 会話への参加: 上記の機能に加えて、ユーザーとアイデアを共有する日常的なコミュニケーションを行うこともできます。
特定のニーズがある場合は、お気軽にお知らせください。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 jsonContent = $@"{{
""input"": {{
""messages"": [
{{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
}},
{{
""role"": ""user"",
""content"": ""Who are you?""
}},
{{
""role"": ""assistant"",
""content"": ""I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.""
}},
{{
""role"": ""user"",
""content"": ""What can you do?""
}}
]
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"リクエスト失敗、ステータスコード: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"DashScope の呼び出しエラー: {ex.Message}");
}
}
}
}サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "a6d041ca3d084a7ca9eff1c456afad70",
"text": "Qwen として、以下を含みますが、これらに限定されないさまざまなタスクを実行するお手伝いができます。\n\n1. 質問への回答: さまざまな知識ベースの質問への回答を提供します。\n2. テキスト生成: 記事、ストーリー、詩、その他のテキストコンテンツを記述します。\n3. 言語翻訳: さまざまな言語間の翻訳作業を実行します。\n4. 会話交換: ユーザーと自然でスムーズな会話を行います。\n5. 提案の提供: ユーザーのニーズに基づいて提案や解決策を提供します。\n\n具体的なニーズがある場合はお知らせください。できる限りお手伝いします。"
},
"usage": {
"models": [
{
"output_tokens": 102,
"model_id": "qwen-max",
"input_tokens": 87
}
]
},
"request_id": "27fb8a01-70d5-974f-bb0a-e9408a9c1772"
}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]interface{}{
"messages": []interface{}{
map[string]string{
"role": "system",
"content": "You are a helpful assistant.",
},
map[string]string{
"role": "user",
"content": "Who are you?",
},
map[string]string{
"role": "assistant",
"content": "I am a large-scale language model developed by Alibaba Cloud, my name is Qwen.",
},
map[string]string{
"role": "user",
"content": "What can you do?",
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("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))
}
}
サンプルレスポンス
{
"output": {
"finish_reason": "stop",
"session_id": "2ae51a5eac3b4b269834cf0695330a05",
"text": "以下を含みますが、これらに限定されないさまざまなタスクを実行するお手伝いができます。\n\n1. 質問への回答: さまざまな分野の知識ベースの質問への回答を提供します。\n2. テキスト作成: ストーリー、記事、詩などを記述します。\n3. プログラミングアシスタント: プログラミングのガイダンスとコード例を提供します。\n4. 会話チャット: 日常会話をしたり、お付き合いしたりします。\n5. 翻訳サービス: 複数の言語間の翻訳サポートを提供します。\n6. 情報クエリ: ニュース、天気予報、履歴データ、その他の情報を見つけます。\n7. 学習ガイダンス: 学習における質問への回答を支援し、学習の提案を提供します。\n\n具体的なニーズや質問がある場合はお知らせください。できる限りお手伝いします。"
},
"usage": {
"models": [
{
"output_tokens": 132,
"model_id": "qwen-max",
"input_tokens": 87
}
]
},
"request_id": "1289eb09-e4ed-9f9e-98ca-805c83b333a1"
}カスタム パラメーターを渡す
同じエージェントまたはワークフローを異なるビジネス シナリオに適応させるために、プラグインまたはノードのカスタム パラメーターを設定し、アプリケーションを呼び出すときに biz_params を介してパラメーターを渡すことができます。パラメーターの設定方法については、「アプリケーション パラメーターのパススルー」をご参照ください。サンプルコード:
カスタム プラグイン パラメーター: 関連付けられた [エージェント アプリケーション] または関連付けられた [ワークフロー アプリケーション] の [プラグイン ノード] を介して渡します。
カスタム プラグインのパラメーターとユーザーレベルの認証情報を渡すことができます。
パラメーター:
user_defined_params.ユーザーレベルの認証:
user_defined_tokens。user_tokenは、プラグインに必要な認証情報です ( DASHSCOPE_API_KEY など)。
次のサンプルは、関連付けられたプラグインの
indexパラメーターとユーザーレベルの認証情報を必要とする [エージェント アプリケーション] です。プラグイン ツールは、同じワークスペース内の [エージェント アプリケーション] にのみ関連付けることができます。
your_plugin_codeをプラグイン カードに表示されている関連付けられたプラグイン ツール ID に置き換え、入力パラメーターのキーと値のペアを渡します。この例では、値が 2 のarticle_indexです。パラメーターの受け渡し
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'参照: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # テキスト出力のみを処理します # print('%s\n' % (response.usage))サンプル レスポンス
The second rule of the Dormitory Convention states: "Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity." This indicates that within the dormitory, members should cultivate a positive atmosphere for living and studying, support and assist each other, and also learn to understand and respect one another. If you need to know about other clauses of the convention, please let me know!Java
サンプル リクエスト
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("参照: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }サンプル レスポンス
Article Two of the Dormitory Convention stipulates: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. This emphasizes that within a shared living environment, roommates should maintain positive relationships and foster a harmonious atmosphere for living and studying through mutual assistance and support. If you need to know more specific clauses, please let me know.HTTP
curl
サンプル リクエスト
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 に置き換えます。
サンプル レスポンス
{"output": {"finish_reason":"stop", "session_id":"e151267ffded4fbdb13d91439011d31e", "text":"「寮の規約」の第 2 条には、「寮生は互いに助け合い、思いやり、学び合い、共に向上し、寛容かつ謙虚で、互いを尊重し、誠意をもって接すること」と記載されています。これは、寮生活において、誰もが互いに支え合い、調和のとれた前向きな生活環境を共に築くべきであることを意味しています。"}, "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]}, "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%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";} } ?>サンプル レスポンス
Article Two of the Dormitory Convention stipulates: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity.This emphasizes that within a shared living environment, roommates should maintain positive relationships and foster a harmonious atmosphere for living and studying through mutual assistance and support. If you need to know more specific clauses, please let me know.Node.js
依存関係:
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("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("リクエストが失敗しました:"); 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=不明なエラー'); } } } catch (error) { console.error(`DashScope の呼び出しエラー: ${error.message}`); if (error.response) { console.error(`レスポンス ステータス: ${error.response.status}`); console.error(`レスポンス データ: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();サンプル レスポンス
The third rule of the Dormitory Convention is as follows: Pay attention to electrical safety, and eliminate fire hazards. The use of open flames, unauthorized electrical appliances, various stoves, and other prohibited items is strictly forbidden in the dormitory. It is also forbidden to store explosive or flammable materials and to privately connect to the power supply. If you need to know more regulations, please let me know.C#
サンプル リクエスト
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}"); } } } }サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "237ca6187c814f3b9e7461090a5f8b74", "text": "寮規約の第二条は以下の通りです。\n \n「寮生は互いに助け合い、思いやり、学び合い、共に向上すべきです。また、寛容かつ謙虚で、互いを尊重し、誠意をもって接しなければなりません。」\n\nこれは、寮内において、メンバーが相互扶助、思いやり、支援を通じて良好な関係を築き、調和のとれた生活と学習の環境を創出する必要があることを示しています。ルームメイト間の違いを理解し受け入れ、誠実にコミュニケーションをとることも重要です。他に知りたい条項や具体的な内容がございましたら、お知らせください。" }, "usage": { "models": [ { "output_tokens": 133, "model_id": "qwen-max", "input_tokens": 829 } ] }, "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79" }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)) } }サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "860d2a4c1f3649ac880298537993cb51", "text": "The second rule of the Dormitory Convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. This emphasizes that in dormitory life, roommates should maintain good mutual assistance while also respecting each other. Would you like to know about other clauses?" }, "usage": { "models": [ { "output_tokens": 84, "model_id": "qwen-max", "input_tokens": 876 } ] }, "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab" }ユーザーレベルの認証
Python
サンプル リクエスト
from http import HTTPStatus import os # 推奨される 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 に置き換え、YOUR_TOKEN を認証情報 (API キーなど) に置き換えます "user_defined_params": { "your_plugin_code": { "article_index": 2}}, "user_defined_tokens": { "your_plugin_code": { "user_token": "YOUR_TOKEN"}}} 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'参照: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # テキスト出力のみを処理します # print('%s\n' % (response.usage))サンプル レスポンス
The second rule of the Dormitory Convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If you need further information on additional rules, please let me know.Java
サンプル リクエスト
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 に置き換え、YOUR_TOKEN を実際のトークン (API キーなど) に置き換えます "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," + "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}"; 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("参照: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }サンプル レスポンス
The second rule of the Dormitory Convention says: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If you need further information on additional rules, please let me know.HTTP
curl
サンプル リクエスト
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 } }, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN" } } } }, "parameters": {}, "debug":{} }'YOUR_APP_ID を実際のアプリケーション ID に置き換えます。
サンプル レスポンス
{"output":{"finish_reason":"stop", "session_id":"d3b5c3e269dc40479255a7a02df5c630", "text":"「寮の規約」の第2条には次のように記載されています。「寮生は互いに助け合い、思いやり、学び合い、共に向上すべきである。寛容で謙虚であり、互いを尊重し、誠意をもって接すること。」これは、寮生活において、誰もが互いに支え合い、調和のとれた前向きな生活環境を共に築くべきであることを意味しています。"}, "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]}, "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%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"; // リクエスト データを構築します $data = [ "input" => [ 'prompt' => 'Dormitory convention content', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [// {your_plugin_code} を実際のプラグイン ID に置き換えます 'article_index' => 2 ] ], 'user_defined_tokens' => [ '{your_plugin_code}' => [// {your_plugin_code} を実際のプラグイン ID に置き換えます 'user_token' => 'YOUR_TOKEN'// 実際のトークン (API キーなど) に置き換えます ] ] ] ], ]; // データを 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";} } ?>サンプル レスポンス
The second rule of the Dormitory Convention is as follows: > Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If you need more information about the convention or other details, please feel free to let me know!Node.js
依存関係:
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': 6 } }, user_defined_tokens: { [pluginCode]: { // YOUR_TOKEN を実際の認証情報 (API キーなど) に置き換えます user_token: 'YOUR_TOKEN' } } } }, parameters: {}, debug: {} }; try { console.log("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("リクエストが失敗しました:"); 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=不明なエラー'); } } } catch (error) { console.error(`DashScope の呼び出しエラー: ${error.message}`); if (error.response) { console.error(`レスポンス ステータス: ${error.response.status}`); console.error(`レスポンス データ: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();サンプル レスポンス
The sixth rule of the Dormitory Convention stipulates: Cultivate good habits regarding daily routines; every dormitory member has the right to rest and the responsibility to ensure others’ rights to rest. If you need more information on the regulations, please let me know.C#
サンプル リクエスト
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 に置き換えます // YOUR_TOKEN を実際のトークン (API キーなど) に置き換えます string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Dormitory convention content"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }}, ""user_defined_tokens"": {{ ""{pluginCode}"": {{ ""user_token"": ""YOUR_TOKEN"" }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("リクエストが成功しました:"); 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}"); } } } }サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "1a1913a9922a401f8eba36df8ea1a062", "text": "The second rule of the Dormitory Convention is as follows: Dormitory members should help each other, care for each other, learn from each other, and improve together; be tolerant, humble, respect each other, and treat each other with sincerity. If there are other clauses or specific contents you want to know, please let me know!" }, "usage": { "models": [ { "output_tokens": 66, "model_id": "qwen-max", "input_tokens": 802 } ] }, "request_id": "04bac806-c5e6-9fab-a846-a66641862be9" }Go
サンプル リクエスト
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": 10, }, }, "user_defined_tokens": map[string]interface{}{ pluginCode: map[string]interface{}{ "user_token": "YOUR_USER_TOKEN", // 実際の認証トークン (API キーなど) に置き換えます }, }, }, }, "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)) } }サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "b8e051ba7e954ff8919208e7b84430fa", "text": "The tenth rule of the Dormitory Convention states that dormitory members should work together to create and maintain a clean, tidy, aesthetically pleasing, and culturally rich dormitory environment. If you need to understand the complete Dormitory Convention content, you may need to check other clauses or directly consult the dormitory management department. Is there any more specific content you would like to know?" }, "usage": { "models": [ { "output_tokens": 70, "model_id": "qwen-max", "input_tokens": 855 } ] }, "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14" }カスタム ノード パラメーター: [ワークフロー アプリケーション] の [開始ノード]、または [エージェント オーケストレーション アプリケーション] の [アプリケーション ノード] を介して渡します。
次のサンプルでは、[ワークフローアプリケーション] の [開始ノード] でパラメーター
cityを定義し、[プロンプト] に変数cityとqueryを挿入してから、アプリケーションを [公開] します。
呼び出すときは、
biz_paramsを介してcityを渡し、promptを介してqueryを渡します。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' # ワークフローおよびエージェント オーケストレーション アプリケーションのカスタム パラメーターの受け渡し biz_params = {"city": "Hangzhou"} response = Application.call( # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることはお勧めしません。API キーが漏洩するリスクを軽減するためです。 api_key=os.getenv("DASHSCOPE_API_KEY"), app_id='YOUR_APP_ID', # 実際のアプリケーション ID に置き換えます prompt='Query the administrative divisions of this city', biz_params=biz_params # ビジネス パラメーターを渡します ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'参照: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print(f'{response.output.text}') # テキスト出力のみを処理しますサンプル レスポンス
The city of Hangzhou, as the capital of Zhejiang Province, has an administrative division consisting of 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own unique characteristics and development focus. - Shangcheng District: Located in the central area of Hangzhou, it is one of the political, economic, and cultural centers of the city. - Gongshu District: Known for its canal culture, it features numerous historical and cultural heritage sites. - Xihu District: Famous for the West Lake scenic area, it is an important destination for tourism. - Binjiang District: A hub for high-tech industries, with renowned companies like Alibaba situated here. - Xiaoshan District: An administrative district in the southeast, experiencing rapid economic growth, particularly in the manufacturing sector. - Yuhang District: Has developed rapidly in recent years, especially in the field of internet economy; Alibaba's headquarters is also located here (Note: Alibaba headquarters is actually in Binjiang District). - Linping District: A newly established district aimed at promoting comprehensive economic and social development in the area. - Qiantang District: Also a result of recent administrative adjustments, focusing on the integration of innovation and ecological protection. - Fuyang District: Located southwest of Hangzhou, known for its rich natural landscapes and long history and culture. - Lin'an District: Situated west of Hangzhou, famous for its beautiful ecological environment and profound cultural heritage. Please note that city planning may change over time, and it is recommended to refer to the latest official information.Java
サンプル リクエスト
import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"Hangzhou\"}"; ApplicationParam param = ApplicationParam.builder() // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコーディングすることはお勧めしません。API キーが漏洩するリスクを軽減するためです。 .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("Query the administrative divisions of this city") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("参照: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }サンプル レスポンス
The city of Hangzhou is the capital of Zhejiang Province and its administrative division mainly includes 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own distinctive characteristics and development focuses. - Shangcheng District: Located in the city center of Hangzhou, it houses many historical and cultural heritage sites. - Gongshu District: Known for its Grand Canal culture, it is also an important commercial and residential area. - Xihu District: Famous for its beautiful natural scenery, including the renowned West Lake scenic area. - Binjiang District: A hub for high-tech industries, home to the Hangzhou National High-Tech Industry Development Zone. - Xiaoshan District: Experiences rapid economic growth, particularly outstanding in the manufacturing sector. - Yuhang District: Has rapidly risen in recent years following the development of high-tech companies like Alibaba. - Linping District: Formed in 2021 from parts of the original Yuhang District, it focuses on ecological construction and technological innovation. - Qiantang District: Also established as a new district in 2021, positioned as the eastern transportation hub and new industrial development area of Hangzhou. - Fuyang District: A cultural city with a long history and one of the important bases for the paper industry. - Lin'an District: Located in the western part of Hangzhou, known for its high forest coverage and good ecological environment. These districts together form the unique geographical layout and socio-economic structure of Hangzhou city. If you are interested in a particular district or need more detailed information, please let me know!HTTP
curl
サンプル リクエスト
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": "Query the administrative divisions of this city", "biz_params": { "city": "Hangzhou"} }, "parameters": {} }'YOUR_APP_ID を実際のアプリケーション ID に置き換えます。
サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "c211219896004b50a1f6f66f2ec5413e", "text": "The city of Hangzhou has jurisdiction over 10 districts, 1 county, and manages 2 county-level cities, which are as follows: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District, Tonglu County, Chun'an County, Jiande City, Zhuji City. Note that Zhuji City is directly under the administration of Zhejiang Province and is jointly managed by both Hangzhou and Shaoxing cities." }, "usage": {}, "request_id": "02c3c9e1-7912-9505-91aa-248d04fb1f5d" }PHP
サンプル リクエスト
<?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' => 'Query the administrative divisions of this city', 'biz_params' => [ 'city' => 'Hangzhou' ] ], ]; // データを 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"; } }サンプル レスポンス
Hangzhou is the capital city of Zhejiang Province and its administrative division mainly includes 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its own unique characteristics and development focuses, such as: - **Shangcheng District** and **Gongshu District** are located in the center of Hangzhou, known for their bustling commerce and rich history. - **Xihu District** is famous for the beautiful West Lake and is also an important area for science, education, and culture. - **Binjiang District** is renowned for its high-tech industry development. - **Xiaoshan District** and **Yuhang District**, among others, have rapidly emerged as new urban districts or economic development zones due to recent city growth. - **Lin'an District** and **Fuyang District** have retained more of the natural scenery and rural charm. Please note that China's administrative divisions may change based on national policies, so please refer to official channels for the latest information.Node.js
依存関係:
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: "Query the administrative divisions of this city", biz_params: { 'city': 'Hangzhou', }, }, parameters: {}, debug: {}, }; try { console.log("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("リクエストが失敗しました:"); 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=不明なエラー'); } } } catch (error) { console.error(`DashScope の呼び出しエラー: ${error.message}`); if (error.response) { console.error(`レスポンス ステータス: ${error.response.status}`); console.error(`レスポンス データ: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();サンプル レスポンス
Hangzhou is the capital city of Zhejiang Province, and its administrative division includes 10 districts, specifically: 1. **Shangcheng District (Shàngchéng Qū)**: Located in the southern part of central Hangzhou, it is one of the city's most historically rich and culturally significant areas. 2. **Gongshu District (Gǒngshù Qū)**: Originally formed from the merger of Xiacheng District and Gongshu District, situated in the northern part of Hangzhou. 3. **Xihu District (Xīhú Qū)**: Known for the World Heritage Site West Lake, featuring abundant natural and cultural landscapes. 4. **Binjiang District (Bīnjiāng Qū)**: Located on the southern bank of the Qiantang River, it is a hub for high-tech industries. 5. **Xiaoshan District (Xiāoshān Qū)**: Situated in the eastern part of Hangzhou, it is one of China's key manufacturing bases. 6. **Yuhang District (Yúháng Qū)**: Once home to Linping, one of China's four famous ancient towns, it has now grown into an important economic development zone in Hangzhou. 7. **Fuyang District (Fùyáng Qū)**: Located in the southwest of Hangzhou, named after the Fuchun River that flows through it. 8. **Lin'an District (Lín'ān Qū)**: Positioned in the mountainous western area of Hangzhou, renowned for its beautiful natural scenery. 9. **Qiantang District (Qiántáng Qū)**: Established in 2021, formed from the former Dajiangdong Industrial Cluster and parts of Xiaoshan District, aimed at fostering development in Hangzhou's eastern region. 10. **Linping District (Lín Píng Qū)**: A new administrative division separated from Yuhang District, mainly covering areas like Linping Street that were originally part of Yuhang District. This information reflects the situation as of my last update. Please note that administrative divisions may change, so refer to the official latest announcements for current information.C#
サンプル リクエスト
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 に置き換えます string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = @"{ ""input"": { ""prompt"": ""Query the administrative divisions of this city"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": {}, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("リクエストが成功しました:"); 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}"); } } } }サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "7a9ff57eec7d475fa5d487de5f5178d2", "text": "Hangzhou is the capital city of Zhejiang Province, and it has jurisdiction over 10 districts: Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, and Lin'an District. Each district has its unique geographical locations and development features. For example, Xihu District is renowned for its beautiful natural scenery, especially the famous West Lake located there; while Binjiang District is more well-known for its high-tech industry development. Additionally, with the city's growth, the administrative divisions may undergo adjustments. Please refer to the latest official announcements for the most current information." }, "usage": { }, "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225" }Go
サンプル リクエスト
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]interface{}{ "prompt": "Query the administrative divisions of this city", "biz_params": map[string]interface{}{ "city": "Hangzhou", }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("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)) } }サンプル レスポンス
{ "output": { "finish_reason": "stop", "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745", "text": "Hangzhou, abbreviated as 'Hang,' is the capital city of Zhejiang Province. According to the latest administrative division adjustments, Hangzhou now oversees 10 districts, 2 county-level cities, and 1 county, specifically: - Districts (10): Shangcheng District, Gongshu District, Xihu District, Binjiang District, Xiaoshan District, Yuhang District, Linping District, Qiantang District, Fuyang District, Lin'an District. - County-level Cities (2): Jiande City, Tonglu County (Note that Tonglu is actually treated as a county-level city here, but more accurately, it is a county). - County (1): Chun'an County. Please be aware that administrative regions may change over time, so please refer to the latest official announcements for the most current information. The above information is compiled based on relatively recent data; for the latest changes, visiting government official websites for the most accurate information is advised." }, "usage": { }, "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02" }
ストリーミング出力
ストリーミング出力モードでは、モデルは中間結果を生成し、最終結果はこれらの複数の中間結果を連結することで形成されます。モデルが出力するにつれて読み取ることができるため、モデルの応答を待つ時間を短縮できます。呼び出し方法に応じて、パラメーターを設定してストリーミング出力を実装できます。
Python SDK:
streamを True に設定します。Java SDK:
streamCallインターフェイスを介して呼び出します。HTTP: ヘッダーで
X-DashScope-SSEをenableとして指定します。
デフォルトでは、ストリーミング出力は非増分です。つまり、各戻り値には、以前に生成されたすべてのコンテンツが含まれます。増分ストリーミング出力を使用するには、incremental_output(incrementalOutputfor Java) パラメーターをtrueに設定します。 HTTP の場合は、incremental_outputを true に設定し、パラメーターオブジェクトに配置します。
例:
[エージェントアプリケーション]:
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'詳細については、ドキュメント https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code を参照してください。') else: print(f'{response.output.text}\n') # テキストのみを出力するための処理レスポンス例
I am Alibaba Cloud 's large-scale language model , my name is Qwen.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("詳細については、ドキュメント https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code を参照してください。"); } System.exit(0); } }レスポンス例
I am Alibaba Cloud 's large-scale language model, my name is Qwen .HTTP
curl
リクエスト例
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 に置き換えます。
レスポンス例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":203,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"am"},"usage":{"models":[{"input_tokens":203,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":203,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":203,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"'s large-scale language"},"usage":{"models":[{"input_tokens":203,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":203,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":203,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}PHP
リクエスト例
<?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 エンコードエラー: " . 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 エラー: " . curl_error($ch)); } // HTTP ステータスコードを取得します $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE); // curl セッションを閉じます curl_close($ch); if ($status_code != 200) { echo "HTTP ステータスコード: $status_code\n"; echo "リクエスト失敗。\n"; } ?>レスポンス例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"I am Alibaba"},"usage":{"models":[{"input_tokens":58,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Cloud"},"usage":{"models":[{"input_tokens":58,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"'s"},"usage":{"models":[{"input_tokens":58,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" a large-scale language"},"usage":{"models":[{"input_tokens":58,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":58,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":58,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}Node.js
依存関係:
npm install axiosリクエスト例
パネルを展開してサンプルコードを表示します。
レスポンス例
1. 完全なレスポンスを出力する
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"Hello!"},"usage":{"models":[{"input_tokens":56,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" Is there"},"usage":{"models":[{"input_tokens":56,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" anything I can"},"usage":{"models":[{"input_tokens":56,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":" help you with?"},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}2. text フィールドのみを出力する
I am Alibaba Cloud 's large-scale language model, I am called Qwen.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("リクエスト成功:"); 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($"リクエスト失敗、ステータスコード: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"DashScope の呼び出しエラー: {ex.Message}"); } } } }レスポンス例
2025-02-14 16:22:08:482 Request successful: 2025-02-14 16:22:09:098 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"I"},"usage":{"models":[{"input_tokens":51,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:099 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" am"},"usage":{"models":[{"input_tokens":51,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:172 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Alibaba"},"usage":{"models":[{"input_tokens":51,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:172 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Cloud's large-scale language"},"usage":{"models":[{"input_tokens":51,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:463 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" model, my name is"},"usage":{"models":[{"input_tokens":51,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:618 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" Qwen"},"usage":{"models":[{"input_tokens":51,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:777 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":". I am your AI"},"usage":{"models":[{"input_tokens":51,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:932 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" assistant,"},"usage":{"models":[{"input_tokens":51,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:091 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" I can answer questions,"},"usage":{"models":[{"input_tokens":51,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:244 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" create text, such as"},"usage":{"models":[{"input_tokens":51,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:389 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" writing stories, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":35,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:525 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" documents, writing"},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:662 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" emails, writing scripts"},"usage":{"models":[{"input_tokens":51,"output_tokens":43,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:902 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":", and I can also express"},"usage":{"models":[{"input_tokens":51,"output_tokens":47,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:062 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":" opinions, play games, etc"},"usage":{"models":[{"input_tokens":51,"output_tokens":51,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:233 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"."},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:309 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:388Go
リクエスト例
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 } } }レスポンス例
id:1 event:result :HTTP_STATUS/200 2025-02-13 18:21:09.050: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"I am"},"usage":{"models":[{"input_tokens":262,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:2 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Tong"},"usage":{"models":[{"input_tokens":262,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:3 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"yi"},"usage":{"models":[{"input_tokens":262,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id:4 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Qianwen, developed by"},"usage":{"models":[{"input_tokens":262,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:5 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" Alibaba Cloud"},"usage":{"models":[{"input_tokens":262,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:6 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":", an AI assistant. I"},"usage":{"models":[{"input_tokens":262,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:7 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" am designed to answer"},"usage":{"models":[{"input_tokens":262,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:8 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.018: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" various questions, provide"},"usage":{"models":[{"input_tokens":262,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:9 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.102: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" information and engage"},"usage":{"models":[{"input_tokens":262,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:10 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.257: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" in conversations. Need"},"usage":{"models":[{"input_tokens":262,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:11 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.414: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":" any help?"},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:12 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.481: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}[ワークフローアプリケーション] は、
flow_stream_modeの値によって決定される 2 つのストリーミング出力モードを提供します。パラメーター値と使用方法:
full_thoughts(デフォルト値):説明: すべてのノードのストリーミング結果が
thoughtsフィールドに出力されます。要件:
has_thoughtsも True に設定する必要があります。
agent_format:説明: エージェントアプリケーションと同じ出力モードです。
効果: コンソールで、特定のノードの [レスポンス] スイッチをオンにすると、そのノードのストリーミング結果が
outputのtextフィールドに含まれます。シナリオ: 特定の中間ノードの出力のみを気にするシナリオに適しています。
[レスポンス] スイッチは、テキスト変換ノード、LLM ノード、および終了ノードでのみ使用できます (終了ノードではデフォルトでスイッチがオンになっています)。ストリーミング出力をサポートしていないノードは、コンテンツを一度に出力します。
例:
full_thoughts
これは、ストリーミング出力を持つ [公開済みワークフローアプリケーション] です。

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' biz_params = { "city": "Hangzhou"} responses = Application.call( # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。 api_key=os.getenv("DASHSCOPE_API_KEY"), # 実際のアプリケーション ID に置き換えます app_id='YOUR_APP_ID', prompt='Hello', biz_params=biz_params, # ストリーミング出力を有効にします stream=True, # incremental_output=true は増分出力を有効にし、false は無効にします。指定しない場合のデフォルトは false です incremental_output=True, # has_thoughts を True に設定する必要があります has_thoughts=True) for response in responses: if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'詳細については、ドキュメント https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code を参照してください。') else: print(f'{response.output.thoughts}\n') # 出力処理をして thoughts のみを返します。プロセス情報は output の thoughts フィールドに返されますレスポンス例
[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_99FA","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"Dongpo\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Pork, West Lake Vinegar Fish,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\" Longjing Shrimp, Hangzhou Pa\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_99FA"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"stry, Beggar\'s Chicken\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_qkYJ","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"West Lake,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Lingyin Temple, Xixi\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" National Wetland Park, Hefang\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\" Street, Hangzhou Botanical Garden\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_qkYJ"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_1","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_99FA","nodeExecTime":"1027ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_2","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_qkYJ","nodeExecTime":"1048ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"End","nodeResult":"{\\"result\\":\\"What do you think about our recommendation?\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]Java
リクエスト例
// 推奨される 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 com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"Hangzhou\"}"; ApplicationParam param = ApplicationParam.builder() // 環境変数が設定されていない場合は、次の行を .apiKey("sk-xxx") に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。 .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") //実際のアプリケーション ID に置き換えます .prompt("Hello") .bizParams(JsonUtils.parse(bizParams)) .incrementalOutput(true) // 増分出力 .hasThoughts(true) // ワークフローアプリケーションでストリーミング出力を実装するには、このパラメーターを true に設定する必要があります。出力結果は thoughts フィールドで確認できます .build(); Application application = new Application(); Flowable<ApplicationResult> result = application.streamCall(param); // ストリーミング出力を実装します result.blockingForEach(data -> { System.out.printf("%s\n",data.getOutput().getThoughts());// 出力処理をして thoughts フィールドのみを表示します }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("詳細については、ドキュメント https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code を参照してください。"); } System.exit(0); } }レスポンス例
[ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_S78u","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"West Lake Fish in Vinegar Sauce,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Longjing Shrimp\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\",Dongpo Pork,Zhiwei Small\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Steamed Buns,Beggar's\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"Chicken\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_5ZzA","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"West Lake,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"Lingyin\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\" Temple,Songcheng\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\",Xixi Wetland,Thousand Island Lake\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"Start","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_jjc0","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_5ZzA","nodeExecTime":"938ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"End","nodeResult":"{\"result\":\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"5ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]HTTP
curl
リクエスト例
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header 'X-DashScope-SSE: enable' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Hello", "biz_params": { "city": "Hangzhou"} }, "parameters": { "has_thoughts": true, "incremental_output": true }, "debug": {} }'YOUR_APP_ID を実際のアプリケーション ID に置き換えます。
レスポンス例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Ling\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"yin Temple,Songcheng,Xixi\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\" National Wetland Park,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Hangzhou Zoo\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1137ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}PHP
リクエスト例
<?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' => 'Hello', 'biz_params' => [ 'city' => 'Hangzhou' ] ], "parameters" => [ 'has_thoughts' => true, // ワークフローアプリケーションとオーケストレーションアプリケーションでは、このパラメーターを true に設定する必要があります。プロセス情報は thoughts に返されます 'incremental_output' => true // 増分出力 ] ]; // データを 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, 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 エラー: " . curl_error($ch)); } // HTTP ステータスコードを取得します $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE); // curl セッションを閉じます curl_close($ch); if ($status_code != 200) { echo "HTTP ステータスコード: $status_code\n"; echo "リクエスト失敗。\n"; } ?>レスポンス例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:2 event:result :200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Ilo9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"Dongpo Pork,Zhiwei Steamed\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"requestid:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_vQDv\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",Hangzhou Tower\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"899ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Hangzhou Tower"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}Node.js
依存関係:
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: "hello", biz_params:{ 'city':'Hangzhou' } }, parameters: { 'incremental_output' : 'true', 'has_thoughts':'true'// ワークフローアプリケーションとエージェントオーケストレーションアプリケーションでストリーミング出力を実装するには、このパラメーターを設定する必要があります }, debug: {} }; try { console.log("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) { console.log("リクエスト成功:"); // ストリーミングレスポンスを処理します response.data.on('data', (chunk) => { console.log(`チャンクを受信しました: ${chunk.toString()}`); }); response.data.on('end', () => { console.log("ストリーム終了。"); }); response.data.on('error', (error) => { console.error(`ストリームエラー: ${error.message}`); }); } else { console.log("リクエスト失敗:"); 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=不明なエラー'); } } } catch (error) { console.error(`DashScope の呼び出しエラー: ${error.message}`); if (error.response) { console.error(`レスポンスステータス: ${error.response.status}`); console.error(`レスポンスデータ: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();レスポンス例
/opt/homebrew/bin/node ./index.js Sending request to DashScope API... Request successful: Received chunk: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" in Vinegar Sauce,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\" Temple,Songcheng,Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"855ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Thousand Island Lake"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Stream ended.C#
リクエスト例
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"": ""Hello"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": { ""incremental_output"": true, ""has_thoughts"": true }, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); try { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = content; HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { Console.WriteLine("リクエスト成功:"); 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($"リクエスト失敗、ステータスコード: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"DashScope の呼び出しエラー: {ex.Message}"); } } } }レスポンス例
2025-02-14 16:55:28:670 Request successful: 2025-02-14 16:55:28:980 {"output":{"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:28:980 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:28:980 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:29:178 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Fish in Vinegar Sauce,Long\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:29:780 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"jing Shrimp,Dongpo Pork,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:29:979 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Zhiwei Steamed Buns,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:30:179 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Beggar's Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:30:379 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:30:986 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"Lingyin Temple,Song\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:31:180 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"cheng,Xixi Wetland,Thousand Island Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:31:382 {"output":{"thoughts":[{"response":"{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"},{"response":"{\"nodeName\":\"End\",\"nodeResult\":\"{\\\"result\\\":\\\"Dear, are you satisfied with my introduction\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"} 2025-02-14 16:55:31:751Go
リクエスト例
package main import ( "bufio" "bytes" "encoding/json" "fmt" "net/http" "os" ) func main() { 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]interface{}{ "prompt": "hello", "biz_params": map[string]interface{}{ "city": "Hangzhou", }, }, "parameters": map[string]interface{}{ "incremental_output": true, "has_thoughts": true, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("JSON のマーシャリングに失敗しました: %v\n", err) return } 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") 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() scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Printf("レスポンスの読み取りエラー: %v\n", err) } if resp.StatusCode != http.StatusOK { fmt.Printf("リクエスト失敗、ステータスコード: %d\n", resp.StatusCode) } }レスポンス例
Request successful: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake Vinegar\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Fish,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Longjing Shrimp\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Dongpo Pork\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Zhiwei Small\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Basket,Beggar's\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Chicken\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"Temple,Songcheng\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Xixi Wetland\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",Qiandao Lake\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:15 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"stop","text":"West Lake,Lingyin Temple,Songcheng,Xixi Wetland,Qiandao Lake"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}thoughts内の各項目は、ノードの実行の詳細です。以下は、LLM ノードの結果の例です。id:7 event:result :HTTP_STATUS/200 data: { "output": { "thoughts": [ { "response": "{\"nodeName\":\"Start\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}" }, { "response": "{\"nodeName\":\"LLM_1\",\"nodeResult\":\"{\\\"result\\\":\\\"Songcheng Fish Soup\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}" }, { "response": "{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}" } ], "session_id": "6035ee0814b64a9fb88346ecaf8b44bf", "finish_reason": "null" }, "usage": { "models": [ { "input_tokens": 25, "output_tokens": 21, "model_id": "qwen-max" } ] }, "request_id": "64825069-b3aa-93a7-bcf1-c66fe57111fd" }LLM ノード (上記の例では LLM_j45e を使用) のストリーミング結果に興味がある場合は、
thoughtsの各プッシュで nodeId LLM_j45e を持つノードの出力に焦点を当てることができます。ノードでエラーが発生した場合、タスク全体も失敗します。
agent_format
これは、[公開済みワークフローアプリケーション] です。[レスポンス] スイッチは最初の [LLM ノード] のみにオンになっており、このノードの結果のみに焦点を当てています。

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' biz_params = { "city": "Hangzhou"} responses = Application.call( # 環境変数が設定されていない場合は、次の行を api_key="sk-xxx" に置き換えます。ただし、本番環境では API キーをコードに直接ハードコードすることは、API キー漏洩のリスクを軽減するために推奨されません。 api_key=os.getenv("DASHSCOPE_API_KEY"), # 実際のアプリケーション ID に置き換えます app_id='YOUR_APP_ID', prompt='Hello', biz_params=biz_params, # ストリーミング出力を有効にします stream=True, # 互換モードを有効にして、指定されたノードのストリーミング結果を出力します flow_stream_mode="agent_format", # incremental_output=true は増分出力を有効にし、false は無効にします。指定しない場合のデフォルトは false です incremental_output=True) for response in responses: if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'詳細については、ドキュメント https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code を参照してください。') else: print(f'{response.output.text}\n') # 出力テキストを処理します。結果は text に返されますレスポンス例
West Lake Fish in Vinegar Sauce, Longjing Shrimp ,Dongpo Pork ,Zhiwei Small Steamed Buns,Beggar's ChickenHTTP
curl
リクエスト例
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header 'X-DashScope-SSE: enable' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "Hello", "biz_params": { "city": "Hangzhou"} }, "parameters": { "incremental_output": true, "flow_stream_mode": "agent_format" }, "debug": {} }'レスポンス例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Fish in Vinegar"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":",Longjing Shrimp,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Pork,Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"4f99497fdde14ac88799cf1f3209b952","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"942a4e9f-1976-9615-ac43-c3a0a1ec58fc"}PHP
リクエスト例
<?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' => 'Hello', 'biz_params' => [ 'city' => 'Hangzhou' ] ], "parameters" => [ 'flow_stream_mode' => 'agent_format', // ワークフローアプリケーションのストリーミング出力互換モードでは、このパラメーターを agent_format に設定します 'incremental_output' => true // 増分出力 ] ]; // データを 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, 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 エラー: " . curl_error($ch)); } // HTTP ステータスコードを取得します $status_code = curl_getinfo($ch, curlINFO_HTTP_CODE); // curl セッションを閉じます curl_close($ch); if ($status_code != 200) { echo "HTTP ステータスコード: $status_code\n"; echo "リクエスト失敗。\n"; } ?>レスポンス例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,Dongpo Pork,"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Zhiwei Steamed Buns,"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"null","text":"Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"8ef1ff3df37646ef9c7b8522e8cba912","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"9cf6539f-32a0-960b-bdfb-1823545edb5f"}Node.js
依存関係:
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: "Hello", biz_params:{ 'city':'Hangzhou' } }, parameters: { 'incremental_output' : 'true', "flow_stream_mode" : "agent_format" }, debug: {} }; try { console.log("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) { console.log("リクエスト成功:"); // ストリーミングレスポンスを処理します response.data.on('data', (chunk) => { console.log(`チャンクを受信しました: ${chunk.toString()}`); }); response.data.on('end', () => { console.log("ストリーム終了。"); }); response.data.on('error', (error) => { console.error(`ストリームエラー: ${error.message}`); }); } else { console.log("リクエスト失敗:"); 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=不明なエラー'); } } } catch (error) { console.error(`DashScope の呼び出しエラー: ${error.message}`); if (error.response) { console.error(`レスポンスステータス: ${error.response.status}`); console.error(`レスポンスデータ: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();レスポンス例
Sending request to DashScope API... Request successful: Received chunk: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Beggar's Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":",Zhiwei Steamed"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"null","text":" Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Received chunk: id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"688dbfb307194b6fa4df7346e7c9eded","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"8f179fcf-b2d2-90a2-97e8-ce0b4fdc8819"} Stream ended.C#
リクエスト例
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"": ""Hello"", ""biz_params"":{ ""city"":""Hangzhou"" } }, ""parameters"": { ""incremental_output"": true, ""flow_stream_mode"": ""agent_format"" }, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); try { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = content; HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { Console.WriteLine("リクエスト成功:"); 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($"リクエスト失敗、ステータスコード: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"DashScope の呼び出しエラー: {ex.Message}"); } } } }レスポンス例
2025-02-14 17:17:09:408 Request successful: 2025-02-14 17:17:10:256 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:257 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Fish in Vinegar Sauce,Longjing Shrimp,"},"usage":{"models":[{"input_tokens":25,"output_tokens":9,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:449 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":"Beggar's Chicken,Dongpo"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:650 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"null","text":" Pork,Zhiwei Steamed Buns"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"} 2025-02-14 17:17:10:850 {"output":{"session_id":"37b12773b63944a5b18e352a9c2cef7d","finish_reason":"stop","text":"Dear, are you satisfied with my introduction"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"aee133b1-9b5e-9658-a91f-380938c4162c"}Go
リクエスト例
package main import ( "bufio" "bytes" "encoding/json" "fmt" "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]interface{}{ "prompt": "Hello", "biz_params": map[string]interface{}{ "city": "Hangzhou", // パラメーター渡し }, }, "parameters": map[string]interface{}{ "incremental_output": true, // このパラメーターを true に設定すると、結果が増分出力されます "flow_stream_mode": "agent_format", // ワークフローアプリケーションで互換モードのストリーミング出力を実装するには、このパラメーターを agent_format に設定する必要があります }, "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") req.Header.Set("X-DashScope-SSE", "enable") // ストリーミング出力リクエストでは、このパラメーターを enable に設定する必要があります // リクエストを送信します client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("リクエストの送信に失敗しました: %v\n", err) return } defer resp.Body.Close() // レスポンスを読み取ります scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Printf("レスポンスの読み取りエラー: %v\n", err) return } // レスポンスを処理します if resp.StatusCode == http.StatusOK { fmt.Println("リクエスト成功:") } else { fmt.Printf("リクエスト失敗、ステータスコード: %d\n", resp.StatusCode) } }レスポンス例
Request successful: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":"West Lake"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Fish in Vinegar Sauce"},"usage":{"models":[{"input_tokens":25,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Longjing Shrimp"},"usage":{"models":[{"input_tokens":25,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Dongpo Pork"},"usage":{"models":[{"input_tokens":25,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":",Zhiwei"},"usage":{"models":[{"input_tokens":25,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Steamed Buns,Beggar's"},"usage":{"models":[{"input_tokens":25,"output_tokens":19,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"null","text":" Chicken"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ec54aef85e8a462396ecf5fce5074ce8","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"1c4955e2-5d0e-9344-a9a7-6b86000eb5da"}
ナレッジベースを取得する
ナレッジベースは、Model Studio の RAG 機能です。モデルの非公開および最新のナレッジを効果的に補完できます。 [エージェントアプリケーション] を呼び出すときに取得範囲を指定して、回答の精度を向上させることができます。
始める前に
Model Studio コンソールで、[エージェントアプリケーション] の [ナレッジベース検索拡張] をオンにします。次に、[公開] アプリケーションをクリックします。
[RAG アプリケーション] では、この前提条件をスキップします。
取得範囲を指定する
指定された ナレッジベースを取得するには、次のいずれかの方法を選択します。
コンソールで、アプリケーションの [ナレッジベースの構成] をクリックし、指定されたナレッジベースを選択します。次に、[公開] アプリケーションをクリックします。
コンソールで指定されたナレッジベースを関連付けないでください。API 呼び出しを行うときに、
rag_optionsを介してナレッジベース ID を渡します。コンソールで指定されたナレッジベースを関連付け、API 呼び出しを行うときに、
rag_optionsを介してナレッジベース ID を渡します。この場合、呼び出し中に渡されたナレッジベースのみが取得されます。たとえば、[エージェントアプリケーション] はナレッジベース A に関連付けられています。ただし、API 呼び出しを行うときにナレッジベース B を指定します。その後、ナレッジベース A は取得されず、ナレッジベース B のみが取得されます。
ナレッジベース ID(pipeline_ids)を取得するには:[ナレッジベースインデックス] ページで取得するか、CreateIndex API によって返される
Data.Idを使用します。CreateIndex は、非構造化ナレッジベースのみをサポートしています。Bailian Phones Specifications.docx は、以下のサンプルで非構造化ナレッジベースとして使用されています。
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'参照:https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # テキスト出力のみを処理します # print('%s\n' % (response.usage))サンプルレスポンス
ご予算に基づいて、**Bailian Zephyr Z9** をお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、ご予算に合っています。軽量 6.4 インチ 1080 x 2340 ピクセルの画面デザイン、128GB ストレージと 6GB RAM を搭載し、日常使いに適しています。さらに、4000mAh バッテリーと 30 倍デジタルズームをサポートするレンズを搭載しており、写真撮影とバッテリー寿命のニーズを満たすことができます。スリムでポータブルな携帯電話で、包括的な機能をお探しなら、Bailian Zephyr Z9 は良い選択です。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("例外: %s", e.getMessage()); System.out.println("参照:https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }サンプルレスポンス
3000 元のご予算内で、**Bailian Zephyr Z9** をお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、ご予算にぴったりです。以下の機能があります。 - **軽量設計**: 6.4 インチ画面は適度なサイズで、片手操作に便利です。 - **バランスの取れたパフォーマンス**: 128GB ストレージと 6GB RAM を搭載し、日常使いに十分です。 - **バッテリー寿命**: 4000mAh バッテリーを搭載し、1 日を通して通常の使用ニーズを満たすことができます。 - **写真撮影機能**: 30 倍デジタルズームレンズを搭載し、遠くの景色を撮影するのに適しています。 ゲーム体験を重視している場合や、その他の特定の要件がある場合はお知らせください。よりパーソナライズされた推奨事項を提供できます。HTTP
curl
サンプルリクエスト
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": "3000 元以下の携帯電話を推奨してください" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"]} }, "debug": {} }'YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に置き換えます。
サンプルレスポンス
{"output":{"finish_reason":"stop","session_id":"d1208af96f9a4d8390e9b29e86f0623c", "text":"3000 元以下の予算の場合、Bailian Zephyr Z9 をお勧めします。 この携帯電話の価格は 2499 ~ 2799 元で、ご予算の要件に完全に合っています。 軽量 6.4 インチ 1080 x 2340 ピクセルディスプレイ、128GB ストレージと 6GB RAM を搭載し、日常使いでさまざまなアプリケーションやマルチタスキングを処理するのに十分です。 さらに、4000mAh バッテリーを搭載し、1 日を通して使用できるようにし、30 倍デジタルズームレンズを搭載し、生活の細部を捉えることができます。 要約すると、Bailian Zephyr Z9 は費用対効果、設計、機能の点で優れた選択肢です。"}, "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]}, "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}%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"; } } ?>サンプルレスポンス
3000 元以下の予算の場合、**Bailian Zephyr Z9** をお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、ご予算にぴったりです。軽量デザイン、6.4 インチ 1080 x 2340 ピクセル画面、128GB ストレージ、6GB RAM を搭載し、日常使いのニーズを十分に満たすことができます。さらに、4000mAh バッテリーにより 1 日を通して通常使用でき、30 倍デジタルズームレンズを搭載して遠くの細部を捉えることができるため、スリムでありながらパワフルです。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(`DashScope の呼び出し中にエラーが発生しました:${error.message}`); if (error.response) { console.error(`レスポンスステータス:${error.response.status}`); console.error(`レスポンスデータ:${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();サンプルレスポンス
3000 元以下の予算の場合、**Bailian Zephyr Z9** を検討することをお勧めします。この携帯電話の参考価格は 3999 ~ 4299 元ですが、プロモーション活動や割引を利用できれば、ご予算の範囲内になる可能性があります。 ### Bailian Zephyr Z9 - 軽量ポータビリティの芸術 - **画面**: 6.4 インチ 1080 x 2340 ピクセル - **ストレージと RAM**: 128GB ストレージ / 6GB RAM - **バッテリー**: 4000mAh - **カメラ**: 30 倍デジタルズームレンズ この携帯電話はスリムでポータブルなデザインで、日常使いに非常に便利で、バッテリー寿命も優れています。費用対効果と日常のユーザーエクスペリエンスを重視している場合は、Bailian Zephyr Z9 は良い選択です。 ご予算が非常に厳しい場合は、e コマースプラットフォームのプロモーション活動に注目するか、同じ価格帯の他のブランドの携帯電話を検討することをお勧めします。これらの提案がお役に立てば幸いです。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 環境変数が設定されていません。");; 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}"); } } } }サンプルレスポンス
{ "output": { "finish_reason": "stop", "session_id": "2344ddc540ec4c5fa110b92d813d3807", "text": "ご予算に基づいて、**Bailian Zephyr Z9** をお勧めします。この携帯電話の参考価格は 2499 ~ 2799 元で、ご予算の要件に合っています。6.4 インチ 1080 x 2340 ピクセル画面、128GB ストレージ、6GB RAM を搭載し、日常使いに十分です。さらに、4000mAh バッテリーにより 1 日を通して通常使用でき、30 倍デジタルズームレンズは遠くの景色を捉えるニーズを満たすことができます。これはスリムでポータブル、かつ機能豊富な選択肢です。" }, "usage": { "models": [ { "output_tokens": 121, "model_id": "qwen-max", "input_tokens": 1841 } ] }, "request_id": "99fceedf-2034-9fb0-aaad-9c837136801f" }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)) } }サンプルレスポンス
{ "output": { "finish_reason": "stop", "session_id": "fadbb4d1fe094ade88985620363506e6", "text": "ご予算に基づいて、**Bailian Zephyr Z9** をお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、3000 元以下の予算に非常に適しています。軽量 6.4 インチ 1080 x 2340 ピクセル画面デザイン、128GB ストレージと 6GB RAM を搭載し、日常使いのニーズを満たすことができます。同時に、4000mAh バッテリーにより 1 日を通して安心して使用でき、30 倍デジタルズームレンズは遠くの細部を捉えることができるため、非常に費用対効果の高い選択肢です。" }, "usage": { "models": [ { "output_tokens": 119, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6" }指定された非構造化ドキュメントを取得する:
rag_optionsにナレッジベース ID、ドキュメント ID、タグ、またはメタデータ(キーと値のペア)を渡します。ドキュメント ID、タグ、およびメタデータは、非構造化ドキュメントに対してのみ有効です。
取得方法:
ドキュメント ID(file_ids):[アプリケーションデータ] ページで確認するか、ドキュメントをインポートするときに AddFile API によって返される ID を使用します。
ドキュメントタグ:[アプリケーションデータ] ページでタグを確認するか、DescribeFile API から取得します。
ドキュメントメタデータ:ナレッジベース ページで、[表示] をクリックしてナレッジベースに入ります。次に、[メタデータ情報] をクリックします。
複数のドキュメント ID を指定できますが、ドキュメントはナレッジインデックスに含まれている必要があります。
ドキュメント ID を指定する場合は、ドキュメントが属するナレッジベース ID も指定する必要があります。
指定されたドキュメントのみが取得されます。たとえば、[エージェントアプリケーション] はナレッジベース A に関連付けられていますが、API 呼び出しではナレッジベース B のドキュメントが指定されています。その後、A のドキュメントは取得されず、B のドキュメントのみが取得されます。
Bailian Phones Specifications.docx は、以下のサンプルで非構造化ナレッジベースとして使用されています。
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 に置き換え、複数ある場合はコンマで区切ります "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"], # 実際の非構造化ドキュメント ID に置き換え、複数ある場合はコンマで区切ります "metadata_filter": { # ドキュメントメタデータのキーと値のペア。複数ある場合はコンマで区切ります "key1": "value1", "key2": "value2" }, "tags": ["tag1", "tag2"] # ドキュメントタグ。複数ある場合はコンマで区切ります } ) if response.status_code != HTTPStatus.OK: print(f'request_id={response.request_id}') print(f'code={response.status_code}') print(f'message={response.message}') print(f'参照:https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output))サンプルレスポンス
{ "text": "3000 元以下の予算内で、**Bailian Zephyr Z9** を検討することをお勧めします。この携帯電話には以下の機能があります。 - **画面**: 6.4 インチ 1080 x 2340 ピクセル。日常使いやエンターテインメントに適しています。 - **メモリとストレージ**: 6GB RAM + 128GB ストレージスペース。ほとんどのユーザーの滑らかさとストレージのニーズを満たすことができます。 - **バッテリー容量**: 4000mAh。1 日を通して使用できることを保証します。 - **カメラ機能**: 30 倍デジタルズームをサポートするレンズを搭載し、より遠くから細部を捉えることができます。 - **その他の機能**: 軽量でポータブルなデザイン、持ち運びが簡単。 参考価格は 2499 ~ 2799 元で、ご予算の要件に完全に合致し、費用対効果に優れています。これらの提案がお役に立てば幸いです。", "finish_reason": "stop", "session_id": "10bdea3d1435406aad8750538b701bee", "thoughts": null, "doc_references": null }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 com.google.gson.JsonObject; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject metadataFilter = new JsonObject(); metadataFilter.addProperty("key1", "value1"); // メタデータのキーと値のペア metadataFilter.addProperty("key2", "value2"); // 複数ある場合は、繰り返し addProperty を呼び出します 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() .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2")) // 実際の指定されたナレッジベース ID に置き換え、複数ある場合はコンマで区切ります .fileIds(List.of("FILE_ID1", "FILE_ID2")) // 実際の指定された非構造化ドキュメント ID に置き換え、複数ある場合はコンマで区切ります .tags(List.of("tags1", "tags2")) // 指定されたドキュメントタグ ID に置き換え、複数ある場合はコンマで区切ります .metadataFilter(metadataFilter) .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("例外: %s", e.getMessage()); System.out.println("参照:https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code"); } System.exit(0); } }サンプルレスポンス
ご予算に基づいて、**Bailian Zephyr Z9** をお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、3000 元前後のご予算の範囲内にぴったりです。 ### Bailian Zephyr Z9 製品のハイライト: - **画面**: 6.4 インチ、1080 x 2340 ピクセル。鮮明で詳細な視覚体験を提供します。 - **ストレージと RAM**: 128GB ストレージスペースと 6GB RAM。日常使いのニーズを満たすのに十分です。 - **バッテリー**: 4000mAh 容量のバッテリーにより、1 日を通して通常使用できます。 - **カメラ**: 30 倍デジタルズームレンズをサポートし、遠くの細部を捉えることができます。 - **デザイン**: 軽量でポータブル。ファッションと利便性を追求するユーザーに適しています。 この携帯電話は適度な価格であるだけでなく、バランスの取れた構成と優れた外観デザインを備えているため、この価格帯では非常に良い選択です。これらの提案がお役に立てば幸いです。その他の要件や質問がある場合は、お気軽にお知らせください。HTTP
curl
サンプルリクエスト
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": "3000 元前後の携帯電話を推奨してください" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"], "file_ids":["YOUR_FILE_ID1"], "metadata_filter":{ "name":"Zhang San"}, "tags":"携帯電話" } }, "debug": {} }'YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に、YOUR_FILE_ID1 を指定された非構造化ドキュメント ID に、metadata_filter のキーと値のペアを実際のメタデータに置き換えます。
サンプルレスポンス
{"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d", "text":"ご予算に基づいて、「Tongyi Vivid 7」を検討することをお勧めします。 6.5 インチ 1080 x 2400 ピクセルの全画面を搭載し、AI インテリジェント写真撮影機能により、プロレベルの色とディテールで写真を撮ることができます。 ハードウェア構成には、8GB RAM と 128GB ストレージスペースが含まれており、スムーズな操作エクスペリエンスを保証します。4500mAh バッテリー容量は、日常使いのニーズにも十分に対応します。 さらに、側面の指紋認証ロックデザインは便利で安全です。参考価格は 2999 ~ 3299 元で、ご予算の範囲内です。"}, "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]}, "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%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 はコンマで区切ります 'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'], // 実際のドキュメント ID に置き換え、複数の ID はコンマで区切ります "metadata_filter" => [ // メタデータのキーと値のペア "key1" => "value1", "key2" => "value2" ], "tags" => ["Tag1", "Tag2"] // ドキュメントタグ ] ] ]; // データを 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"; } } ?>サンプルレスポンス
ご予算に基づいて、**Bailian Zephyr Z9** をお勧めします。この携帯電話の参考価格は 2499 ~ 2799 元で、3000 元以下の要件にぴったりです。軽量 6.4 インチ 1080 x 2340 ピクセルデザイン、128GB ストレージ、6GB RAM を搭載し、日常使いのニーズを満たすことができます。さらに、4000mAh バッテリーを搭載し、1 日を通して安心して使用でき、30 倍デジタルズームレンズを搭載して遠くの細部を捉えることができるため、薄型でありながらパワフルな選択肢です。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 = '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 に置き換え、複数の ID はコンマで区切ります file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // 指定されたファイル ID に置き換え、複数の ID はコンマで区切ります metadata_filter:{ // メタデータのキーと値のペア。複数のペアはコンマで区切ります 'key1':'value1', 'key2':'value2' }, tags: ['tag1', 'tag2'] // ドキュメントタグ。複数のタグはコンマで区切ります } }, 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(`DashScope の呼び出し中にエラーが発生しました:${error.message}`); if (error.response) { console.error(`レスポンスステータス:${error.response.status}`); console.error(`レスポンスデータ:${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();サンプルレスポンス
3000 元以下の予算内で、**Bailian Zephyr Z9** を検討することをお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、スリムでポータブルなデザイン、6.4 インチ 1080 × 2340 ピクセル画面、128GB ストレージ、6GB RAM を搭載し、日常使いのニーズを満たすことができます。4000mAh バッテリーにより 1 日を通して使用でき、30 倍デジタルズームレンズはより遠くから細部を捉えるのに役立ちます。全体的に、これは価値の高い選択肢です。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 環境変数が設定されていません。");; string appId = "YOUR_APP_ID";// 実際のアプリケーション ID に置き換えます // YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に置き換え、YOUR_FILE_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""], ""file_ids"":[""YOUR_FILE_ID1""], ""metadata_filter"":{{ ""name"":""Zhang San"" }}, ""tags"":""携帯電話"" }} }}, ""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}"); } } } }サンプルレスポンス
{ "output": { "finish_reason": "stop", "session_id": "be9b5a1964fe41c9bbfd8674226bd238", "text": "ご予算に基づいて、**Bailian Zephyr Z9** をお勧めします。この携帯電話の価格は 2499 ~ 2799 元で、3000 元以下の予算に非常に適しています。 ### 製品のハイライト - **スリムなデザイン**: 1080 x 2340 ピクセルの解像度を持つ 6.4 インチ画面を搭載し、持ち運びが簡単な洗練された外観を備えています。 - **バランスの取れたパフォーマンス**: 6GB RAM と 128GB ストレージスペースを搭載し、日常使いのニーズを満たすことができます。 - **長持ちするバッテリー**: 内蔵 4000mAh バッテリーにより、1 日を通して通常使用できます。 - **優れた写真撮影**: 30 倍デジタルズーム機能をサポートし、遠くの景色や細部を簡単に捉えることができます。 基本的なニーズを満たしながら特定の機能も備えた、費用対効果の高いスマートフォンをお探しなら、Bailian Zephyr Z9 は良い選択です。" }, "usage": { "models": [ { "output_tokens": 180, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "d0811195-0b3f-931e-90b8-323a65053d9c" }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 に置き換えます "file_ids": []string{"YOUR_FILE_ID1"}, // 指定された非構造化ドキュメント ID に置き換えます "metadata_filter": map[string]string{ "name": "Zhang San", // メタデータのキーと値のペア }, "tags": "携帯電話", // 非構造化データドキュメントタグ }, }, "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)) } }サンプルレスポンス
{ "output": { "finish_reason": "stop", "session_id": "9de268b3d84748b5ac6321aba72b6ecd", "text": "ご予算に基づいて、**Bailian Zephyr Z9** を検討することをお勧めします。この携帯電話の参考価格は 2499 ~ 2799 元で、3000 元以下のニーズに非常に適しています。以下の機能があります。 - 軽量 6.4 インチ 1080 x 2340 ピクセル画面デザイン。 - 128GB ストレージと 6GB RAM を搭載し、日常使いのニーズを満たすことができます。 - 4000mAh バッテリーを搭載し、1 日を通して通常使用できます。 - リアカメラは 30 倍デジタルズームレンズをサポートし、遠くの細部を捉えることができます。 写真撮影やゲームに特に高い要件がない場合は、Bailian Zephyr Z9 は良い選択です。" }, "usage": { "models": [ { "output_tokens": 156, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "8940b597-92e1-9471-b4eb-896e563c479d" }
構造化ドキュメントから指定されたデータを取得します。
rag_optionsでナレッジベース ID と「構造化データヘッダー + 値」のキーと値のペアを渡します。構造化データのキーと値のペアを取得します(structured_filter): ナレッジベース ページで、[表示] をクリックしてナレッジベースに入ります。次に、[インデックスの表示] をクリックします。
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='Please recommend a mobile phone under 3000 yuan', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # 実際のナレッジベース ID に置き換えます。複数ある場合はカンマで区切ります "structured_filter": { # 構造化データのキーと値のペア。構造化データに対応します。複数ある場合はカンマで区切ります "key1": "value1", "key2": "value2" } } ) 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": "I recommend the \"Bailian\" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information, such as performance, appearance, etc., please let me know.", "finish_reason": "stop", "session_id": "80a3b868b5ce42c8a12f01dccf8651e2", "thoughts": null, "doc_references": null }Java
リクエスト例
// 推奨 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 com.google.gson.JsonObject; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject structureFilter = new JsonObject(); structureFilter.addProperty("key1", "value1"); // 構造化データのキーと値のペア structureFilter.addProperty("key2", "value2"); // 複数ある場合は、繰り返し addProperty を呼び出します ApplicationParam param = ApplicationParam.builder() // 環境変数が構成されていない場合は、次の行を .apiKey("sk-xxx") に置き換えることができます。ただし、本番環境では API キーをコードに直接ハードコードすることはお勧めしません。API キーが漏洩するリスクを軽減するためです。 .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // 実際のアプリケーション ID に置き換えます .prompt("Please recommend a mobile phone around 3000 yuan") .ragOptions(RagOptions.builder() .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2")) // 実際の指定されたナレッジベース ID に置き換えます。複数ある場合はカンマで区切ります .structuredFilter(structureFilter) .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); } }レスポンス例
I recommend the "Bailian" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need to know more information about this phone, such as configuration, performance, etc., please let me know, and I will provide you with more detailed information.HTTP
curl
リクエスト例
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 around 3000 yuan" }, "parameters": { "rag_options" : { "pipeline_ids":["YOUR_PIPELINE_ID1"], "structured_filter":{ "price":"2999"} } }, "debug": {} }'YOUR_APP_ID を実際のアプリケーション ID に、YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に置き換えます。
レスポンス例
{"output":{"finish_reason":"stop","session_id":"d6bc4206f9cc4d368d534f8aa4e502bc", "text":"I recommend a mobile phone priced close to 3000 yuan:\n\n- **Bailian phone**, priced at 2999 yuan. \n\nThis phone offers good value for money and meets your budget requirements. If you need more detailed information about this phone or have other specific requirements (such as camera performance, processor model, etc.), please let me know, and I will try to provide more comprehensive information."}, "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%PHP
リクエスト例
<?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' => 'Please help me recommend a smartphone under 3000 yuan.' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // 指定されたナレッジベース ID に置き換えます。複数ある場合はカンマで区切ります "structured_filter" => [ // 構造化データのキーと値のペア。複数ある場合はカンマで区切ります "key1" => "value1", "key2" => "value2" ] ] ] ]; // データを 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"; } } ?>レスポンス例
I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more information about this phone, please let me know.Node.js
依存関係:
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 に置き換えます // YOUR_PIPELINE_ID1 を指定されたナレッジベース ID に置き換えます。複数のナレッジベース ID はカンマで区切ります const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "Please recommend a mobile phone under 3000 yuan" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], structured_filter:{ 'key1':'value1', 'key2':'value2' } } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();レスポンス例
I recommend the "Bailian" phone, which is priced at 2999 yuan, fitting your budget requirement. If you need to know more details or have other specific requirements, please let me know!C#
リクエスト例
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("Please make sure DASHSCOPE_API_KEY is set."); return; } string url = $"https://dashscope-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""Please recommend a mobile phone under 3000 yuan"" }}, ""parameters"": {{ ""rag_options"" : {{ ""pipeline_ids"":[""YOUR_PIPELINE_ID1""], ""structured_filter"":{{ ""price"":""2999"" }} }} }}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }レスポンス例
{ "output": { "finish_reason": "stop", "session_id": "108e9104568e44f1915fb3d3d44fdc92", "text": "I recommend the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other suggestions, please let me know." }, "usage": { "models": [ { "output_tokens": 38, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "d6d103f4-5c22-9782-9682-45d51a5607f9" }Go
リクエスト例
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 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 mobile phone under 3000 yuan", }, "parameters": map[string]interface{}{ "rag_options": map[string]interface{}{ "pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // 指定された構造化ナレッジベース ID に置き換えます "structured_filter": map[string]string{ "price": "2999", // 構造化データのキーと値のペア }, }, }, "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)) } }レスポンス例
{ "output": { "finish_reason": "stop", "session_id": "9e0a031b51d1492e8b613ca391b445b0", "text": "I recommend you consider the \"Bailian\" phone, which is priced at 2999.0 yuan, fitting your budget requirement. If you need more information about this phone or other recommendations, please let me know." }, "usage": { "models": [ { "output_tokens": 39, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54" }
情報を表示する
取得プロセスを表示する:呼び出しを行うときに、
has_thoughtsをコードに追加し、True に設定します。取得プロセスは、outputのthoughtsフィールドに返されます。回答ソースを表示する:[エージェントアプリケーション] の [取得構成] で [ソースを表示] をオンにし、アプリケーションを公開します。

API リファレンス
パラメーターの完全なリストについては、「アプリケーション呼び出し API」をご参照ください。
エラーコード
呼び出しが失敗し、エラーメッセージが返された場合は、トラブルシューティングについてエラーメッセージをご参照ください。
参考資料
API/SDK を使用して RAG アプリケーションを呼び出すためのローコードメソッドについては、「ローコードで RAG アプリケーションを迅速に構築する」をご参照ください。
選択するモデルについては、「モデル」をご参照ください。
アプリケーションの構築と使用方法については、「アプリケーションの概要」をご参照ください。
アプリケーションのプロンプトエンジニアリングツールについては、「プロンプトエンジニアリング」をご参照ください。