本文介紹如何在阿里雲百鍊的 智能体应用 和 工作流应用 (智能體編排應用已被工作流程應用替代)調用中使用自訂參數傳遞功能,主要適用於自訂外掛程式與自訂節點的參數傳遞。
您需要已擷取API Key並配置API Key到環境變數。如果通過SDK調用,還需要安裝DashScope SDK。請將範例程式碼中的
下方樣本展示在智能体应用中如何傳遞自訂外掛程式參數。
下方樣本展示在工作流应用中,傳遞開始節點的自訂參數。
DASHSCOPE_API_HOST 替換為擷取的 API Host。
自訂外掛程式參數傳遞
本文以寢室公約內容查詢工具作為樣本,向您展示API如何調用應用的自訂外掛程式參數傳遞功能。自訂外掛程式的參數通過關聯的智能体应用傳遞,或通過工作流应用中的外掛程式節點傳遞。
如何使用
步驟一:建立自訂外掛程式工具
如果已建立外掛程式工具或已匯入了外掛程式,請跳過此步驟。
-
建立自訂外掛程式:訪問百鍊控制台的外掛程式頁面,單擊新增自定义插件,填寫外掛程式資訊,如需要鑒權請開啟是否鉴权開關,填寫鑒權配置資訊。
樣本外掛程式描述:寢室公約查詢工具,可以根據輸入的數字索引查詢特定條目。
樣本外掛程式 URL:https://domitorgreement-plugin-example-icohrkdjxy.cn-beijing.fcapp.run
樣本鑒權配置:鑒權類型選擇使用者級鑒權,位置選擇Header,Type 選擇 basic。 請注意:插件描述是對外掛程式用途的簡要說明,能協助大模型判斷當前任務是否需要調用當前外掛程式,請使用自然語言進行描述。 -
建立工具:填寫工具資訊,配置輸入參數和輸出參數。請注意:
- 工具描述能協助大模型更好的理解工具功能和使用情境。請使用自然語言進行描述,盡量給出使用樣本。
- 参数名称儘可能帶有含義,可以協助大模型理解當前需要識別的參數資訊是什麼。
- 参数描述是對該入參的功能描述,要簡練且準確,協助大模型進一步理解取參的方式。
- 輸入參數的传参方式務必選擇业务透传。
article_index設定為業務透傳參數。 將工具名稱填入Dormitory convention query tool,請求方法選擇 POST,提交方式選擇 application/json。將輸入參數article_index的類型設為 Number、傳遞方式設為 Body,並標記為必填。輸出參數部分,名稱填入article、描述填入 "宿舍公約內容",類型設為 String。 - 點擊 Test Tool,執行通過後將外掛程式發佈。
步驟二:智能體應用關聯指定外掛程式
外掛程式工具只能與位於相同業務空間裡的智能体应用關聯。
- 可在發行的外掛程式卡片上單擊添加到智能体,選擇需要關聯的智能體應用;
- 也可在應用內單擊+外掛程式,關聯指定的自訂外掛程式;
- 然後直接发布應用。
步驟三:API調用
-
無需鑒權時:通過API調用自訂外掛程式,使用
biz_params的user_defined_params傳遞自訂外掛程式資訊,your_plugin_code替換為實際的外掛程式ID,並傳遞外掛程式中配置的輸入參數索引值對。外掛程式ID可在外掛程式卡片上擷取。
本樣本中傳入寢室公約索引article_index參數值為2,查詢第二條寢室公約內容,並返回正確結果。- Python
- Java
- HTTP
請求樣本響應樣本Copyimport os import dashscope # dashscope 2.0.1 or later is required. from dashscope import DashScopeError # The following is the configuration for the Singapore (ap-southeast-1) region. The region value varies by region. client = dashscope.Client( # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". We recommend using an environment variable in production to avoid leaking your API key. api_key=os.getenv("DASHSCOPE_API_KEY"), region="ap-southeast-1") biz_params = { # Pass the input parameters for the agent application's custom plugin. Replace `your_plugin_code` with your plugin ID. "user_defined_params": { "your_plugin_code": { "article_index": 2}}} try: response = client.apps.completions.create( app_id='YOUR_APP_ID', prompt='寝室公约内容', biz_params=biz_params) print('%s\n' % (response.text)) # Process and output only the text. # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy寝室公约的第二条规定如下: "寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。" 这表明在寝室内,成员之间应该培养一种积极正面的生活和学习氛围,彼此帮助和支持,同时也要学会理解和尊重他人。如果您需要了解公约的其他条款,请告诉我!請求樣本響應樣本Copyimport 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 = // Pass the input parameters for the agent application's custom plugin. Replace `{your_plugin_code}` with your plugin ID. "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}"; ApplicationParam param = ApplicationParam.builder() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("寝室公约内容") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy寝室公约的第二条规定如下: 第二条 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 这强调了在共同生活环境中,室友之间应该保持积极正面的关系,通过相互帮助和支持来营造一个和谐的生活和学习氛围。如果有更多具体的条款需要了解,请告知我。- curl
- PHP
- Node.js
- C#
- Go
請求樣本Copycurl -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": "寝室公约内容", "biz_params": { "user_defined_params": { "{your_plugin_code}": { "article_index": 2 } } } }, "parameters": {}, "debug":{} }'YOUR_APP_ID替換為實際的應用 ID。
響應樣本Copy{"output": {"finish_reason":"stop", "session_id":"e151267ffded4fbdb13d91439011d31e", "text":"寝室公约的第二条内容是:“寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。”这意呀着在寝室生活中,大家要彼此支持,共同创造一个和谐、积极向上的生活环境。"}, "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]}, "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%請求樣本響應樣本Copy<?php # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; //Replace {your_plugin_code} with your plugin ID. // Construct request data $data = [ "input" => [ 'prompt' => '寝室公约内容', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [ 'article_index' => 2 ] ] ] ], ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options 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 ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response 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";} } ?>Copy寝室公约的第二条规定:寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。这是为了保证大家能在一个和谐友爱的环境中生活和学习。如果有更多具体的条款需要了解,或者有其他问题,随时可以问我!需安裝相關依賴:請求樣本Copynpm install axios響應樣本Copyconst axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "寝室公约内容", biz_params: { user_defined_params: { [pluginCode]: { // article_index is a variable for the custom plug-in, replace with the actual plug-in variable 'article_index': 3 } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Copy寝室公约的第三条规定如下: 注意安全用电,杜绝火灾隐患。寝室内严禁使用明火、违规电器、各种灶具以及其他违规物品,不得存放易爆、易燃物品,私接电源。 如果您需要了解更多的规定,请告诉我。請求樣本響應樣本Copyusing System.Text; class Program { static async Task Main(string[] args) { // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application 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}"; // Replace `{your_plugin_code}` with your plugin ID. string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""寝室公约内容"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }} }} }}, ""parameters"": {{}}, ""debug"": {{}} }}"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Copy{ "output": { "finish_reason": "stop", "session_id": "237ca6187c814f3b9e7461090a5f8b74", "text": "寝室公约的第二条规定如下: "寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。" 这表示在寝室内,成员之间需要建立起一种积极正面的关系,通过帮助、关心和支持彼此来营造一个和谐的生活和学习环境。同时也要学会理解和接受室友之间的差异,以真诚的态度去交流沟通。如果还有其他条款或具体内容想要了解,请告诉我!" }, "usage": { "models": [ { "output_tokens": 133, "model_id": "qwen-max", "input_tokens": 829 } ] }, "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79" }請求樣本響應樣本Copypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "寝室公约内容", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 2, }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request 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() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Handle response 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)) } }Copy{ "output": { "finish_reason": "stop", "session_id": "860d2a4c1f3649ac880298537993cb51", "text": "寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 这强调了在宿舍生活中,室友之间应该保持良好的互助关系,同时也要互相尊重对方。您想要了解其他条款的内容吗?" }, "usage": { "models": [ { "output_tokens": 84, "model_id": "qwen-max", "input_tokens": 876 } ] }, "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab" } -
需要鑒權時:通過API調用自訂外掛程式,外掛程式中開啟了鉴权開關,配置了用户级鉴权。
外掛程式ID在外掛程式卡片上擷取。
- 使用
biz_params的user_defined_params傳遞自訂外掛程式資訊,your_plugin_code替換為實際的外掛程式ID,並傳入外掛程式中配置的輸入參數索引值對。 - 使用
biz_params的user_defined_tokens傳遞相關資訊,your_plugin_code替換為實際的外掛程式ID,user_token的參數值填入鑒權資訊,如實際DASHSCOPE_API_KEY的值。 - 鑒權通過後根據傳遞的索引參數查詢特定條目並正確返回結果。
article_index參數值為2,user_token的值YOUR_TOKEN替換為實際DASHSCOPE_API_KEY的值。鑒權通過後,查詢第二條寢室公約內容,並返回正確結果。- Python
- Java
- HTTP
請求樣本響應樣本Copyimport os import dashscope # dashscope 2.0.1 or later is required. from dashscope import DashScopeError # The following is the configuration for the Singapore (ap-southeast-1) region. The region value varies by region. client = dashscope.Client( # If the environment variable is not set, you can use your Model Studio API key by replacing the following line with api_key="sk-xxx". We recommend using an environment variable in production to avoid leaking your API key. api_key=os.getenv("DASHSCOPE_API_KEY"), region="ap-southeast-1") biz_params = { # Pass the authentication information for the agent application's custom plugin. Replace `your_plugin_code` with your plugin ID and replace `YOUR_TOKEN` with the authentication information, such as an API key. "user_defined_params": { "your_plugin_code": { "article_index": 2}}, "user_defined_tokens": { "your_plugin_code": { "user_token": "YOUR_TOKEN"}}} try: response = client.apps.completions.create( app_id='YOUR_APP_ID', prompt='寝室公约内容', biz_params=biz_params) print('%s\n' % (response.text)) # Process and output only the text. # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如果您需要了解更多的规定内容,请告诉我。請求樣本響應樣本Copyimport 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 = // Replace {your_plugin_code} with your plugin ID, and YOUR_TOKEN with your token, such as an API key. "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," + "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}"; ApplicationParam param = ApplicationParam.builder() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") .prompt("寝室公约内容") .bizParams(JsonUtils.parse(bizParams)) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText()); } public static void main(String[] args) { try { appCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如果您需要查询更多的规定内容,请告诉我。應用ID替換YOUR_APP_ID,自訂的外掛程式ID替換your_plugin_code,鑒權Token替換YOUR_TOKEN。
- curl
- PHP
- Node.js
- C#
- Go
請求樣本Copycurl -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": "寝室公约内容", "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,自訂的外掛程式ID替換your_plugin_code,鑒權Token替換YOUR_TOKEN。
響應樣本Copy{"output":{"finish_reason":"stop", "session_id":"d3b5c3e269dc40479255a7a02df5c630", "text":"寝室公约的第二条内容为:“寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。”这强调了寝室生活中成员之间和谐相处与共同进步的重要性。"}, "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]}, "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%請求樣本響應樣本Copy<?php # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => '寝室公约内容', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [//Replace {your_plugin_code} with your plugin ID. 'article_index' => 2 ] ], 'user_defined_tokens' => [ '{your_plugin_code}' => [//Replace {your_plugin_code} with your plugin ID. 'user_token' => 'YOUR_TOKEN'//Replace with the actual Token, such as API key ] ] ] ], ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options 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 ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response 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";} } ?>Copy寝室公约的第二条规定如下: > 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如果需要了解更多的公约内容或其他信息,请随时告诉我!需安裝相關依賴:請求樣本Copynpm install axios響應樣本Copyconst axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const pluginCode = 'YOUR_PLUGIN_CODE';// Replace with the actual plug-in ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "寝室公约内容", biz_params: { user_defined_params: { [pluginCode]: { // article_index is a variable for the custom plug-in, replace with the actual plug-in variable 'article_index': 6 } }, user_defined_tokens: { [pluginCode]: { // Replace YOUR_TOKEN with the actual authentication information, such as API key user_token: 'YOUR_TOKEN' } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Copy寝室公约的第六条规定:养成良好的作息习惯,每一位寝室成员都享有休息的权利和承担保证他人休息权利和义务。如果你需要了解更多的规定内容,请进一步说明。請求樣本響應樣本Copyusing System.Text; class Program { static async Task Main(string[] args) { // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application 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"; // Replace your_plugin_code with your plugin ID. // Replace YOUR_TOKEN with the actual Token, such as API key string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""寝室公约内容"", ""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("Request successful:"); Console.WriteLine(responseBody); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Copy{ "output": { "finish_reason": "stop", "session_id": "1a1913a9922a401f8eba36df8ea1a062", "text": "寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如需了解更详细的公约内容,请进一步指明。" }, "usage": { "models": [ { "output_tokens": 66, "model_id": "qwen-max", "input_tokens": 802 } ] }, "request_id": "04bac806-c5e6-9fab-a846-a66641862be9" }請求樣本響應樣本Copypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID pluginCode := "YOUR_PLUGIN_CODE" // Replace with the actual plug-in ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "寝室公约内容", "biz_params": map[string]interface{}{ "user_defined_params": map[string]interface{}{ pluginCode: map[string]interface{}{ "article_index": 10, }, }, "user_defined_tokens": map[string]interface{}{ pluginCode: map[string]interface{}{ "user_token": "YOUR_USER_TOKEN", // Replace with the actual authentication token, such as API key }, }, }, }, "parameters": map[string]interface{}{}, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request 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() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Handle response 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)) } }Copy{ "output": { "finish_reason": "stop", "session_id": "b8e051ba7e954ff8919208e7b84430fa", "text": "寝室公约的第十条规定,寝室成员应共同努力,营造和维护内务整洁干净、美观、高文化品味的寝室环境。如果需要了解完整的寝室公约内容,可能还需要查看其他条款或直接咨询宿舍管理部门。对于更多具体内容,您还有想要了解的部分吗?" }, "usage": { "models": [ { "output_tokens": 70, "model_id": "qwen-max", "input_tokens": 855 } ] }, "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14" } - 使用
自訂節點參數傳遞
本文以根據城市名查詢城市行政地區劃分作為樣本,向您展示API如何調用應用的自訂節點參數傳遞功能。應用的自訂節點參數通過工作流应用的開始節點傳遞。
如何使用
步驟一:自訂節點參數
在 工作流 開啟目標應用程式。在开始節點新增String 類型的變數 city。將 city 和 query 插入提示詞,然後發布應用程式。
步驟二:API調用
調用時通過biz_params欄位傳遞city,通過prompt欄位傳遞query。
- Python
- Java
- HTTP
請求樣本響應樣本
Copy
import os
import dashscope
from dashscope import DashScopeError
# The following is the configuration for the Singapore (ap-southeast-1) region. The region value varies by region.
client = dashscope.Client(
# If you have not configured an environment variable, you can use your Model Studio API key by replacing the following line with: api_key="sk-xxx".
# We recommend that you do not hardcode the API key in your code in a production environment to reduce the risk of API key leaks.
api_key=os.getenv("DASHSCOPE_API_KEY"),
region="ap-southeast-1")
# Pass custom parameters for a workflow application.
biz_params = {"city": "杭州"}
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID', # Replace with your actual application ID.
prompt='查询这个城市的行政区域划分',
biz_params=biz_params # Pass business parameters.
)
print(f'{response.text}') # Process and output only the text.
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Copy
杭州市,作为浙江省的省会城市,其行政区域划分包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有其独特的特色和发展重点。
- 上城区:位于杭州市中心地带,是杭州的政治、经济、文化中心之一。
- 拱墅区:以运河文化为特色,拥有众多历史文化遗产。
- 西湖区:著名的西湖风景区就位于此区,是旅游观光的重要目的地。
- 滨江区:高新技术产业聚集地,阿里巴巴等知名企业坐落于此。
- 萧山区:东南部的一个行政区,经济发展迅速,特别是制造业方面。
- 余杭区:近年来发展快速,尤其是互联网经济领域,阿里巴巴总部也设在这里(注:阿里巴巴总部实际位于滨江区)。
- 临平区:新成立的行政区,旨在促进该地区经济社会全面发展。
- 钱塘区:同样是一个较新的行政区划调整结果,强调创新发展和生态保护相结合。
- 富阳区:位于杭州西南方向,以其丰富的自然景观和悠久的历史文化著称。
- 临安区:地处杭州西部,以生态优美闻名,并且有着深厚的文化底蕴。
请注意,随着时间推移,具体的城市规划可能会有所变化,请参考最新的官方信息。
請求樣本響應樣本
Copy
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\":\"杭州\"}";
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("查询这个城市的行政区域划分")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Copy
杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有自己的特色和发展重点。
- 上城区:位于杭州市中心,拥有许多历史文化遗产。
- 拱墅区:以大运河文化而闻名,同时也是一个重要的商业和居住区。
- 西湖区:以其美丽的自然风光著称,包括著名的西湖风景区。
- 滨江区:高新技术产业集聚地,杭州国家高新技术产业开发区就设在这里。
- 萧山区:经济发展迅速,尤其在制造业方面表现突出。
- 余杭区:近年来随着阿里巴巴等高科技企业的发展而快速崛起。
- 临平区:2021年由原余杭区部分区域调整而来,注重生态建设和科技创新。
- 钱塘区:同样是在2021年成立的新区,定位为杭州东部交通枢纽及产业发展新高地。
- 富阳区:历史悠久的文化名城,也是造纸业的重要基地之一。
- 临安区:位于杭州西部,森林覆盖率高,生态环境良好。
这些区域共同构成了杭州市独特的地理格局和社会经济结构。如果你对某个特定区域感兴趣或需要更详细的信息,请告诉我!
- curl
- PHP
- Node.js
- C#
- Go
請求樣本
Copy
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": "查询这个城市的行政区域划分",
"biz_params": {
"city": "杭州"}
},
"parameters": {}
}'
YOUR_APP_ID替換為實際的應用 ID。響應樣本
Copy
{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e",
"text":"杭州市下辖10个区、1个县,代管2个县级市,分别为:
上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区、桐庐县、淳安县、建德市、诸暨市。
注意,诸暨市由浙江省直辖、杭州市与绍兴市共同管理。"},"usage":{},
"request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}
請求樣本響應樣本
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => '查询这个城市的行政区域划分',
'biz_params' => [
'city' => '杭州'
]
],
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
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
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
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";
}
}
Copy
杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。
每个区都有自己的特色和发展重点,比如:
- **上城区**和**拱墅区**位于杭州市中心,商业繁华,历史悠久。
- **西湖区**以美丽的西湖而闻名,同时也是一个重要的科教文化区。
- **滨江区**则以其高新技术产业发展著称。
- **萧山区**、**余杭区**等则是近年来随着城市发展迅速崛起的新城区或经济开发区。
- **临安区**、**富阳区**等地则更多保留了自然风光与乡村风貌。
请注意,中国的行政区划可能会根据国家政策调整有所变化,请通过官方渠道获取最新信息。
需安裝相關依賴:請求樣本響應樣本
Copy
npm install axios
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID'; // Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "查询这个城市的行政区域划分",
biz_params: {
'city': '杭州',
},
},
parameters: {},
debug: {},
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Copy
杭州市是浙江省的省会,其行政区域划分包括10个市辖区。具体如下:
1. 上城区(Shàngchéng Qū):位于杭州市中心偏南,是杭州历史最悠久、文化底蕴最深厚的区域之一。
2. 拱墅区(Gǒngshù Qū):原为下城区和拱墅区合并而成的新区,位于杭州市北部。
3. 西湖区(Xīhú Qū):以世界文化遗产西湖而闻名,拥有丰富的自然与人文景观。
4. 滨江区(Bīnjiāng Qū):地处钱塘江南岸,是一个高新技术产业集聚地。
5. 萧山区(Xiāoshān Qū):位于杭州市东部,是中国重要的制造业基地之一。
6. 余杭区(Yúháng Qū):曾经是中国四大名镇之一的临平所在地,现已成为杭州重要的经济发展区。
7. 富阳区(Fùyáng Qū):位于杭州市西南部,因富春江穿流其间而得名。
8. 临安区(Lín'ān Qū):位于杭州市西部山区,以其美丽的自然风光著称。
9. 钱塘区(Qiántáng Qū):成立于2021年,由原大江东产业集聚区及部分萧山区组成,旨在促进杭州东部地区的发展。
10. 临平区(Lín Píng Qū):从余杭区分设出来的一个新行政区划,主要涵盖原余杭区内的临平街道等地。
以上信息反映了截至我最后更新时的情况,请注意行政区划可能会有所调整,请以官方发布的最新消息为准。
請求樣本響應樣本
Copy
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application 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"": ""查询这个城市的行政区域划分"",
""biz_params"":{
""city"":""杭州""
}
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Copy
{
"output": {
"finish_reason": "stop",
"session_id": "7a9ff57eec7d475fa5d487de5f5178d2",
"text": "杭州市是浙江省的省会,它下辖有10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区和临安区。每个区都有其独特的地理位置和发展特色。例如,西湖区以美丽的自然风光著称,尤其是著名的杭州西湖就位于此;而滨江区则更多地以其高新技术产业发展闻名。此外,随着城市的发展,行政区划也可能会有所调整,请关注官方发布的最新信息。"
},
"usage": {
},
"request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225"
}
請求樣本響應樣本
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "查询这个城市的行政区域划分",
"biz_params": map[string]interface{}{
"city": "杭州",
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
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()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle response
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))
}
}
Copy
{
"output": {
"finish_reason": "stop",
"session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745",
"text": "杭州市,简称“杭”,是浙江省的省会城市。根据最新的行政区划调整,杭州市现辖10个市辖区、2个县级市和1个县,具体如下:
- 市辖区(10个):上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。
- 县级市(2个):建德市、桐庐县(注意这里的桐庐实际上被列为县级市处理,但准确地说它是一个县)。
- 县(1个):淳安县。
请注意,随着时间的变化,行政区域可能会有所调整,请以官方最新发布的消息为准。上述信息基于较新的资料整理而来,对于最新的变动情况,建议访问政府官方网站获取最准确的信息。"
},
"usage": {
},
"request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02"
}