リクエストボディ | テキスト入力Pythonimport os
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# これはシンガポールリージョンのベース URL です。
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'Who are you?'}
]
response = dashscope.Generation.call(
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-plus", # 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
messages=messages,
result_format='message'
)
print(response)
Java// DashScope SDK バージョン 2.12.0 以降が必要です。
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
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.protocol.Protocol;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
// これはシンガポールリージョンのベース URL です。
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Who are you?")
.build();
GenerationParam param = GenerationParam.builder()
// DASHSCOPE_API_KEY が設定されていない場合、代わりに .apiKey("sk-xxx") を使用します。
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// 例外をログ出力します。
System.err.println("Generation サービスエラー: " + e.getMessage());
}
System.exit(0);
}
}
PHP (HTTP)<?php
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// 必要に応じて qwen-plus を別のモデルに置き換えます。モデル一覧については、https://www.alibabacloud.com/help/zh/model-studio/getting-started/models をご参照ください。
"model" => "qwen-plus",
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
],
"parameters" => [
"result_format" => "message"
]
];
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo "Response: " . $response;
} else {
echo "Error: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>
Node.js (HTTP)DashScope は Node.js 向けの SDK を提供していません。OpenAI Node.js SDK を使用する場合は、「OpenAI」セクションをご参照ください。 import fetch from 'node-fetch';
// シンガポール、米国 (バージニア)、北京リージョン間で API キーは異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
$apiKey = getenv('DASHSCOPE_API_KEY');
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus", // ここでは qwen-plus を例として使用しています。必要に応じてモデル名を置き換えてください。モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Who are you?"
}
]
},
parameters: {
result_format: "message"
}
};
fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(JSON.stringify(data));
})
.catch(error => {
console.error('Error:', error);
});
C# (HTTP)using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// DASHSCOPE_API_KEY が設定されていない場合、代わりに string? apiKey = "sk-xxx" を使用します。
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
$apiKey = getenv('DASHSCOPE_API_KEY');
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API キーが設定されていません。DASHSCOPE_API_KEY 環境変数を設定してください。");
return;
}
string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 必要に応じて qwen-plus を別のモデルに置き換えます。モデル一覧については、https://www.alibabacloud.com/help/zh/model-studio/getting-started/models をご参照ください。
string jsonContent = @"{
""model"": ""qwen-plus"",
""input"": {
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
},
""parameters"": {
""result_format"": ""message""
}
}";
// リクエストを送信し、レスポンスを取得します。
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// 結果を出力します。
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// リクエストヘッダーを設定します。
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// リクエストを送信し、レスポンスを取得します。
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// レスポンスを処理します。
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"リクエスト失敗: {response.StatusCode}";
}
}
}
}
Go (HTTP)DashScope は Go 向けの SDK を提供していません。OpenAI Go SDK を使用する場合は、「OpenAI-Go」セクションをご参照ください。 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Input struct {
Messages []Message `json:"messages"`
}
type Parameters struct {
ResultFormat string `json:"result_format"`
}
type RequestBody struct {
Model string `json:"model"`
Input Input `json:"input"`
Parameters Parameters `json:"parameters"`
}
func main() {
// HTTP クライアントを作成します。
client := &http.Client{}
// リクエストボディを構築します。
requestBody := RequestBody{
// 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
Model: "qwen-plus",
Input: Input{
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "Who are you?",
},
},
},
Parameters: Parameters{
ResultFormat: "message",
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// POST リクエストを作成します。
req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// リクエストヘッダーを設定します。
// DASHSCOPE_API_KEY が設定されていない場合、代わりに apiKey := "sk-xxx" を使用します。
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// リクエストを送信します。
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// レスポンスボディを読み取ります。
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// レスポンスを出力します。
fmt.Printf("%s\n", bodyText)
}
curlAPI キーはリージョン固有です。「API キーの作成 curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message"
}
}'
ストリーミング出力「ストリーミング出力」をご参照ください。 テキスト生成モデルPythonimport os
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?'}
]
responses = dashscope.Generation.call(
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
model="qwen-plus",
messages=messages,
result_format='message',
stream=True,
incremental_output=True
)
for response in responses:
print(response)
Javaimport java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
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 java.lang.System;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static void handleGenerationResult(GenerationResult message) {
System.out.println(JsonUtils.toJson(message));
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// DASHSCOPE_API_KEY が設定されていない場合、代わりに .apiKey("sk-xxx") を使用します。
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
.model("qwen-plus")
.messages(Arrays.asList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.incrementalOutput(true)
.build();
}
public static void main(String[] args) {
try {
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("例外が発生しました: {}", e.getMessage());
}
System.exit(0);
}
}
curlcurl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-SSE: enable" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
},
"parameters": {
"result_format": "message",
"incremental_output":true
}
}'
マルチモーダルモデルPythonimport os
from dashscope import MultiModalConversation
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"text": "What does the image show?"}
]
}
]
responses = MultiModalConversation.call(
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='qwen3-vl-plus', # 別のマルチモーダルモデルに置き換える必要がある場合は、対応するメッセージも更新してください。
messages=messages,
stream=True,
incremental_output=True)
full_content = ""
print("ストリーミング出力:")
for response in responses:
if response["output"]["choices"][0]["message"].content:
print(response.output.choices[0].message.content[0]['text'])
full_content += response.output.choices[0].message.content[0]['text']
print(f"完全な内容: {full_content}")
Javaimport java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
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 ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
// 可変マップを作成する必要があります。
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
Collections.singletonMap("text", "What does the image show?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
// DASHSCOPE_API_KEY が設定されていない場合、代わりに .apiKey("sk-xxx") を使用します。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-vl-plus") // 別のマルチモーダルモデルに置き換える必要がある場合は、対応するメッセージも更新してください。
.messages(Arrays.asList(userMessage))
.incrementalOutput(true)
.build();
Flowable<MultiModalConversationResult> result = conv.streamCall(param);
result.blockingForEach(item -> {
try {
var content = item.getOutput().getChoices().get(0).getMessage().getContent();
// コンテンツが存在し、空でないことを確認します。
if (content != null && !content.isEmpty()) {
System.out.println(content.get(0).get("text"));
}
} catch (Exception e){
System.exit(0);
}
});
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curlcurl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-DashScope-SSE: enable' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"text": "What does the image show?"}
]
}
]
},
"parameters": {
"incremental_output": true
}
}'
画像入力大規模言語モデルを用いた画像分析のその他の方法については、「画像および動画理解」をご参照ください。 Pythonimport os
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
{"text": "What are these?"}
]
}
]
response = dashscope.MultiModalConversation.call(
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 必要に応じて qwen-vl-max を別のモデルに置き換えます。モデル一覧については、https://www.alibabacloud.com/help/zh/model-studio/getting-started/models をご参照ください。
model='qwen-vl-max',
messages=messages
)
print(response)
Java// Copyright (c) Alibaba, Inc. and its affiliates.
import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
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 simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"),
Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"),
Collections.singletonMap("text", "What are these?"))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// DASHSCOPE_API_KEY が設定されていない場合、代わりに .apiKey("sk-xxx") を使用します。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 必要に応じて qwen-vl-plus を別のモデルに置き換えます。モデル一覧については、https://www.alibabacloud.com/help/zh/model-studio/getting-started/models をご参照ください。
.model("qwen-vl-plus")
.message(userMessage)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curlAPI キーはリージョン固有です。「API キーの作成 curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "qwen-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
{"text": "What are these?"}
]
}
]
}
}'
動画入力次の例では、動画フレームを渡す方法を示しています。動画ファイルを渡すなどの他の方法については、「視覚的理解」をご参照ください。 Pythonimport os
# DashScope SDK バージョン 1.20.10 以降が必要です。
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [{"role": "user",
"content": [
# Qwen2.5-VL シリーズモデルの場合、画像リストを渡すと、fps を設定することで、元の動画から 1/fps 秒間隔で画像を抽出したことを示すことができます。
{"video":["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
"fps":2},
{"text": "Describe the specific process in this video"}]}]
response = dashscope.MultiModalConversation.call(
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
api_key=os.getenv("DASHSCOPE_API_KEY"),
model='qwen2.5-vl-72b-instruct', # 必要に応じて qwen2.5-vl-72b-instruct を別のモデルに置き換えます。モデル一覧については、https://www.alibabacloud.com/help/zh/model-studio/models をご参照ください。
messages=messages
)
print(response["output"]["choices"][0]["message"].content[0]["text"])
Java// DashScope SDK バージョン 2.18.3 以降を使用します。
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String MODEL_NAME = "qwen2.5-vl-72b-instruct"; // 必要に応じて qwen2.5-vl-72b-instruct を別のモデルに置き換えます。モデル一覧については、https://www.alibabacloud.com/help/zh/model-studio/models をご参照ください。
public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage systemMessage = MultiModalMessage.builder()
.role(Role.SYSTEM.getValue())
.content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
.build();
// Qwen2.5-VL シリーズモデルの場合、画像リストを渡すと、fps を設定することで、元の動画から 1/fps 秒間隔で画像を抽出したことを示すことができます。
Map<String, Object> params = Map.of(
"video", Arrays.asList("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"),
"fps",2);
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
params,
Collections.singletonMap("text", "Describe the specific process in this video")))
.build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// DASHSCOPE_API_KEY が設定されていない場合、代わりに .apiKey("sk-xxx") を使用します。
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL_NAME)
.messages(Arrays.asList(systemMessage, userMessage)).build();
MultiModalConversationResult result = conv.call(param);
System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
}
public static void main(String[] args) {
try {
videoImageListSample();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curlAPI キーはリージョン固有です。「API キーの作成 curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen2.5-vl-72b-instruct",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"video": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
],
"fps":2
},
{
"text": "Describe the specific process in this video"
}
]
}
]
}
}'
ツール呼び出し完全な関数呼び出しワークフローについては、「テキスト生成モデルの概要」をご参照ください。 Pythonimport os
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "現在時刻を知りたいときに便利です。",
"parameters": {}
}
},
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "指定された都市の天気を照会したいときに便利です。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "都市または郡(例:北京、杭州、余杭区)"
}
}
},
"required": [
"location"
]
}
}
]
messages = [{"role": "user", "content": "How is the weather in Hangzhou?"}]
response = dashscope.Generation.call(
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
model='qwen-plus',
messages=messages,
tools=tools,
result_format='message'
)
print(response)
Javaimport java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.aigc.conversation.ConversationParam.ResultFormat;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public class GetWeatherTool {
private String location;
public GetWeatherTool(String location) {
this.location = location;
}
public String call() {
return location+" has clear skies today.";
}
}
public class GetTimeTool {
public GetTimeTool() {
}
public String call() {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String currentTime = "Current time: " + now.format(formatter) + ".";
return currentTime;
}
}
public static void SelectTool()
throws NoApiKeyException, ApiException, InputRequiredException {
SchemaGeneratorConfigBuilder configBuilder =
new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
.without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
SchemaGenerator generator = new SchemaGenerator(config);
ObjectNode jsonSchema_weather = generator.generateSchema(GetWeatherTool.class);
ObjectNode jsonSchema_time = generator.generateSchema(GetTimeTool.class);
FunctionDefinition fdWeather = FunctionDefinition.builder().name("get_current_weather").description("Get the weather for a specified location")
.parameters(JsonUtils.parseString(jsonSchema_weather.toString()).getAsJsonObject()).build();
FunctionDefinition fdTime = FunctionDefinition.builder().name("get_current_time").description("Get the current time")
.parameters(JsonUtils.parseString(jsonSchema_time.toString()).getAsJsonObject()).build();
Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
.content("You are a helpful assistant. When asked a question, use tools wherever possible.")
.build();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("Hangzhou weather").build();
List<Message> messages = new ArrayList<>();
messages.addAll(Arrays.asList(systemMsg, userMsg));
GenerationParam param = GenerationParam.builder()
// API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
.model("qwen-plus")
.messages(messages)
.resultFormat(ResultFormat.MESSAGE)
.tools(Arrays.asList(
ToolFunction.builder().function(fdWeather).build(),
ToolFunction.builder().function(fdTime).build()))
.build();
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
// これはシンガポールリージョンのベース URL です。
GenerationResult result = gen.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
SelectTool();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(String.format("Exception %s", e.getMessage()));
}
System.exit(0);
}
}
curlAPI キーはリージョン固有です。「API キーの作成 この例の URL はシンガポールリージョン用です。 curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input": {
"messages": [{
"role": "user",
"content": "How is the weather in Hangzhou?"
}]
},
"parameters": {
"result_format": "message",
"tools": [{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Useful when you want to know the current time.",
"parameters": {}
}
},{
"type": "function",
"name": "get_current_weather",
"description": "指定された都市の天気を照会したいときに便利です。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "都市または郡(例:北京、杭州、余杭区)"
}
}
},
"required": ["location"]
}
}]
}
}'
非同期呼び出し# DashScope Python SDK バージョン 1.19.0 以降を使用します。
import asyncio
import platform
import os
import dashscope
from dashscope.aigc.generation import AioGeneration
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# これはシンガポールリージョンのベース URL です。
async def main():
response = await AioGeneration.call(
# DASHSCOPE_API_KEY 環境変数が設定されていない場合、
# 次の行を api_key="sk-xxx" に置き換えます。
# API キーはリージョンごとに異なります。API キーの取得方法については、https://www.alibabacloud.com/help/zh/model-studio/get-api-key をご参照ください。
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 必要に応じて qwen-plus を置き換えます — モデル一覧: https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
model="qwen-plus",
messages=[{"role": "user", "content": "Who are you?"}],
result_format="message",
)
print(response)
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
ドキュメント理解Pythonimport os
import dashscope
# 中国 (北京) リージョンのみが qwen-long-latest モデルをサポートしています。
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'you are a helpful assisstant'},
# {FILE_ID} をご利用の会話で使用される実際のファイル ID に置き換えます。
{'role':'system','content':f'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'What is this article about?'}]
response = dashscope.Generation.call(
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-long-latest",
messages=messages,
result_format='message'
)
print(response)
Javaimport os
import dashscope
# 中国 (北京) リージョンのみが qwen-long-latest モデルをサポートしています。
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'you are a helpful assisstant'},
# {FILE_ID} をご利用の会話で使用される実際のファイル ID に置き換えます。
{'role':'system','content':f'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'What is this article about?'}]
response = dashscope.Generation.call(
# DASHSCOPE_API_KEY が設定されていない場合、代わりに api_key="sk-xxx" を使用します。
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-long-latest",
messages=messages,
result_format='message'
)
print(response)
curlドキュメント理解モデルは、中国 (北京) リージョンでのみサポートされています。 {FILE_ID} をご利用の会話で使用される実際のファイル ID に置き換えます。 curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-long-latest",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "system",
"content": "fileid://{FILE_ID}"
},
{
"role": "user",
"content": "What is this article about?"
}
]
},
"parameters": {
"result_format": "message"
}
}'
|