阿里云百煉(1) : 阿里云百煉應用問答_回答圖片問題_方案1_提問時上傳圖片文件

直接用于拍照答題不大理想, 可能適用其他用途, 更好的方案:?阿里云百煉(1) : 阿里云百煉應用問答_回答圖片問題_方案2_提取題目再提問-CSDN博客

1.實現代碼

package cn.nordrassil.ly.test.拍照答題;import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.app.RagOptions;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.bailian20231229.AsyncClient;
import com.aliyun.sdk.service.bailian20231229.models.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;public class 阿里云百煉應用問答_回答圖片問題_方案1_提問時上傳圖片文件 {private static Map<String, String> params = new HashMap<>();static {params.put("accessKeyId", "");params.put("accessKeySecret", "");params.put("workspaceId", "");params.put("apiKey", "");params.put("appId", "");params.put("filePath", "C:\\Users\\admin\\Pictures\\1.png");}public static void main(String[] args) throws Exception {init();/* 1.上傳文件 *//** 1.1.申請文檔上傳租約 **/StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()// Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set..accessKeyId(params.get("accessKeyId")).accessKeySecret(params.get("accessKeySecret"))//.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token.build());// Configure the ClientAsyncClient client = AsyncClient.builder().region("cn-beijing") // Region ID//.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient).credentialsProvider(provider)//.serviceConfiguration(Configuration.create()) // Service-level configuration// Client-level configuration rewrite, can set Endpoint, Http request parameters, etc..overrideConfiguration(ClientOverrideConfiguration.create()// Endpoint 請參考 https://api.aliyun.com/product/bailian.setEndpointOverride("bailian.cn-beijing.aliyuncs.com")//.setConnectTimeout(Duration.ofSeconds(30))).build();// Parameter settings for API requestApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = ApplyFileUploadLeaseRequest.builder().categoryType("SESSION_FILE").categoryId("default").fileName(params.get("fileName")).md5(params.get("fileMd5")).sizeInBytes(params.get("fileLength")).workspaceId(params.get("workspaceId"))// Request-level configuration rewrite, can set Http request parameters, etc.// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders())).build();// Asynchronously get the return value of the API requestCompletableFuture<ApplyFileUploadLeaseResponse> response = client.applyFileUploadLease(applyFileUploadLeaseRequest);// Synchronously get the return value of the API requestApplyFileUploadLeaseResponse resp = response.get();System.out.println("- 申請文檔上傳租約結果: " + new Gson().toJson(resp));ApplyFileUploadLeaseResponseBody.Param param = resp.getBody().getData().getParam();/** 1.2.上傳文檔至阿里云百煉的臨時存儲 **/HttpURLConnection connection = null;try {// 創建URL對象URL url = new URL(param.getUrl());connection = (HttpURLConnection) url.openConnection();// 設置請求方法用于文檔上傳,需與您在上一步中調用ApplyFileUploadLease接口實際返回的Data.Param中Method字段的值一致connection.setRequestMethod("PUT");// 允許向connection輸出,因為這個連接是用于上傳文檔的connection.setDoOutput(true);JSONObject headers = JSONObject.parseObject(JSONObject.toJSONString(param.getHeaders()));connection.setRequestProperty("X-bailian-extra", headers.getString("X-bailian-extra"));connection.setRequestProperty("Content-Type", headers.getString("Content-Type"));// 讀取文檔并通過連接上傳try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());FileInputStream fileInputStream = new FileInputStream(params.get("filePath"))) {byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = fileInputStream.read(buffer)) != -1) {outStream.write(buffer, 0, bytesRead);}outStream.flush();}// 檢查響應int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 文檔上傳成功處理System.out.println("- 上傳文件成功");} else {// 文檔上傳失敗處理System.out.println("Failed to upload the file. ResponseCode: " + responseCode);}} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {connection.disconnect();}}/** 1.3.將文檔添加至阿里云百煉的數據管理 **/AddFileRequest addFileRequest = AddFileRequest.builder().categoryType("SESSION_FILE").leaseId(resp.getBody().getData().getFileUploadLeaseId()).parser("DASHSCOPE_DOCMIND").categoryId("default").workspaceId(params.get("workspaceId"))// Request-level configuration rewrite, can set Http request parameters, etc.// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders())).build();// Asynchronously get the return value of the API requestCompletableFuture<AddFileResponse> addFileresponse = client.addFile(addFileRequest);// Synchronously get the return value of the API requestAddFileResponse addFileresp = addFileresponse.get();System.out.println("- 將文檔添加至阿里云百煉的數據管理結果: " + new Gson().toJson(addFileresp));// Asynchronous processing of return values/*response.thenAccept(resp -> {System.out.println(new Gson().toJson(resp));}).exceptionally(throwable -> { // Handling exceptionsSystem.out.println(throwable.getMessage());return null;});*/// Finally, close the clientString fileId = addFileresp.getBody().getData().getFileId();System.out.println("- fileId: " + fileId);/** 1.4.查看文件是否解析 **/DescribeFileRequest describeFileRequest = DescribeFileRequest.builder().workspaceId(params.get("workspaceId")).fileId(fileId)// Request-level configuration rewrite, can set Http request parameters, etc.// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders())).build();// Asynchronously get the return value of the API requestString status = null;while (status == null || !status.equals("FILE_IS_READY")) {CompletableFuture<DescribeFileResponse> describeResponse = client.describeFile(describeFileRequest);// Synchronously get the return value of the API requestDescribeFileResponse describeResp = describeResponse.get();if (describeResp.getBody() == null) {continue;}if (describeResp.getBody().getData() == null) {continue;}status = describeResp.getBody().getData().getStatus();if (status == null) {continue;}System.out.println("- fileId狀態: " + status);Thread.sleep(500);}// 關閉client.close();/* 2.調用百煉應用 */ApplicationParam aiParam = ApplicationParam.builder()// 若沒有配置環境變量,可用百煉API Key將下行替換為:.apiKey("sk-xxx")。但不建議在生產環境中直接將API Key硬編碼到代碼中,以減少API Key泄露風險。.apiKey(params.get("apiKey")).appId(params.get("appId")) // 替換為實際的應用ID.prompt("請直接輸出圖片問題的答案, 無需多言").ragOptions(RagOptions.builder().sessionFileIds(Arrays.asList(fileId))  // 替換為實際指定的臨時文件 ID,逗號隔開多個.build()).build();Application application = new Application();ApplicationResult result = application.call(aiParam);System.out.printf("%s\n",result.getOutput().getText());// 處理只輸出文本textSystem.out.println();}private static void init() throws Exception {String filePath = params.get("filePath");File file = new File(filePath);if (!file.exists()) {System.err.println("文件[" + filePath + "]不存在");System.exit(1);}params.put("fileMd5", getMD5Checksum(file));params.put("fileLength", String.valueOf(file.length()));params.put("fileName", file.getName());}public static String getMD5Checksum(File file) throws IOException, NoSuchAlgorithmException {FileInputStream fis = new FileInputStream(file);MessageDigest digest = MessageDigest.getInstance("MD5");FileChannel fileChannel = fis.getChannel();MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());// 使用MappedByteBuffer可以更高效地讀取大文件digest.update(buffer);byte[] hashBytes = digest.digest();// 將字節數組轉換為十六進制字符串StringBuilder hexString = new StringBuilder();for (byte b : hashBytes) {String hex = Integer.toHexString(0xff & b);if (hex.length() == 1) hexString.append('0');hexString.append(hex);}fileChannel.close();fis.close();return hexString.toString();}
}

2.依賴

        <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version><scope>compile</scope></dependency><!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java --><dependency><groupId>com.alibaba</groupId><artifactId>dashscope-sdk-java</artifactId><version>2.20.1</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>alibabacloud-bailian20231229</artifactId><version>2.0.6</version></dependency>

3.百煉應用提示詞

# 角色
你是一位知識淵博的專家,能夠根據用戶的需求提供準確、詳細且有幫助的答案。你具備廣泛的知識背景,并能靈活運用這些知識來解答各種問題。## 技能
### 技能 1: 知識檢索與應用
- 根據用戶的問題,從知識庫中檢索相關信息。### 技能 2: 問題解答
- 理解用戶的問題意圖和需求。
- 提供詳細、準確的答案,解釋關鍵概念和邏輯。## 限制
- 回答問題時必須基于現有的知識庫
- 知識庫中沒有的回復"知識庫無相關信息"# 知識庫
請記住以下材料,他們可能對回答問題有幫助。
${documents}

4.測試

4.1.創建知識庫導入文檔

百煉控制臺

點擊[中國人民解放軍海軍福建艦_百度百科]保存為pdf導入知識庫

4.2.創建應用綁定知識庫

4.3.準備問題圖片

4.4.測試

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/84180.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/84180.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/84180.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

深入探索 CSS 中的偽類:從基礎到實戰?

在前端開發的世界里&#xff0c;CSS 作為網頁樣式的 “化妝師”&#xff0c;有著至關重要的作用。而 CSS 偽類則像是這位 “化妝師” 手中的神奇畫筆&#xff0c;能夠基于元素的狀態或位置為其添加獨特的樣式&#xff0c;極大地豐富了網頁的交互性和視覺效果。接下來&#xff0…

c++ constexpr關鍵字

constexpr字面意思為常量表格式&#xff0c; 用于指示編譯器在編譯時計算表達式的值。 1、作為常量表格式&#xff0c;必須在編譯時就能確定其值。如&#xff1a;constexpr int size 9527; 2、可以修飾函數&#xff0c;要求能在編譯時求值&#xff0c;所以傳的參數也必須是編…

服務器硬盤分類

以下是服務器硬盤的綜合性分類與技術特性分析&#xff0c;依據當前行業標準及技術演進整理&#xff1a; 一、按存儲介質分類 1. ?機械硬盤&#xff08;HDD&#xff09;? ? 核心特性?&#xff1a;采用旋轉磁盤與機械磁頭結構&#xff0c;通過磁道尋址實現數據讀寫 …

圖解深度學習 - 機器學習簡史

前言 深度學習并非總是解決問題的最佳方案&#xff1a;缺乏足夠數據時&#xff0c;深度學習難以施展&#xff1b;某些情況下&#xff0c;其他機器學習算法可能更為高效。 若初學者首次接觸的是深度學習&#xff0c;可能會形成一種偏見&#xff0c;視所有機器學習問題為深度學…

ConceptAttention:Diffusion Transformers learn highly interpretable features

ConceptAttention: Diffusion Transformers Learn Highly Interpretable Featureshttps://arxiv.org/html/2502.04320?_immersive_translate_auto_translate=1用flux的attention來做圖文的顯著性分析。 1.i

【Python正則表達式終極指南】從零到工程級實戰

目錄 &#x1f31f; 前言&#x1f3d7;? 技術背景與價值&#x1fa79; 當前技術痛點&#x1f6e0;? 解決方案概述&#x1f465; 目標讀者說明 &#x1f9e0; 一、技術原理剖析&#x1f4ca; 核心概念圖解&#x1f4a1; 核心作用講解&#x1f527; 關鍵技術模塊說明?? 技術選…

C++對象的內存模型

C++對象的內存模型涉及對象的數據成員(包括靜態成員和非靜態成員)、成員函數以及虛函數表等在內存中的布局和管理方式。以下是C++對象的內存模型的主要組成部分: 1. C++對象的組成 一個C++對象通常由以下幾個部分組成: 非靜態數據成員 對象的核心組成部分,每個對象都有自己…

hugging-face數據集快速下載

開發機配置外網代理并使用 git lfs 高速下載 Hugging Face 數據集流程 本文檔將介紹如何配置開發機的代理&#xff0c;登錄 Hugging Face&#xff0c;并使用 git-lfs &#xff08;Git Large File Storage&#xff09;進行數據集的高速下載。 1. 配置代理連接外網 開發機在某些…

17、Python對象操作全解析:同一運算符、成員運算符與整數緩存機制實戰

適合人群&#xff1a;零基礎自學者 | 編程小白快速入門 閱讀時長&#xff1a;約8分鐘 文章目錄 一、問題&#xff1a;Python 同一運算符的本質與實戰&#xff1f;1、例子1&#xff1a;雙胞胎身份證驗證2、答案&#xff1a;&#xff08;1&#xff09;is 同一運算符介紹&#xff…

使用auto-coder將kotti項目的pyramid依賴從1.x升級到2.x,將SQLALchemy從1.x升級到2.x

緣起 kotti是一個非常好的基于pyramid框架的web搭建項目&#xff0c;但是由于作者離世&#xff0c;已經3年沒有更新了。 嘗試使用auto-coder將kotti項目的pyramid依賴從1.x升級到2.x&#xff0c;同時發現SQLALchemy依賴也有問題&#xff0c;將SQLALchemy從1.x升級到2.x 開始…

luckysheet的使用——17.將表格作為pdf下載到本地

luckysheet源碼里面自帶有打印按鈕&#xff0c;但是功能是無法使用的&#xff0c;所以我把該功能重寫了一遍 1.在menuButton.js文件中找到源碼打印按鈕的觸發事件&#xff1a; $("#luckysheet-icon-print").click(function () {}2.使用自己寫的掛載方法 window.pr…

仿真APP助力提升卡車駕駛室駕乘舒適度與安全性

駕駛室作為卡車的重要組成部分&#xff0c;其振動特性對于駕駛員的舒適度和長期健康具有至關重要的影響。振動不僅會導致駕駛員疲勞、分散注意力&#xff0c;還可能引發一系列健康問題。為了確保卡車在復雜路面工況下駕駛室結構不受破壞&#xff0c;并保持良好的NVH性能&#x…

功能強大且易于使用的 JavaScript 音頻庫howler.js 和AI里如何同時文字跟音頻構思想法

howler.js 是一個功能強大且易于使用的 JavaScript 音頻庫&#xff0c;它提供了跨瀏覽器的音頻播放功能&#xff0c;支持多種音頻格式&#xff0c;并且具有豐富的 API&#xff0c;可以方便地控制音頻的播放、暫停、循環、音量等。下面是如何在 Vue 項目中使用 howler.js 實現音…

JUC入門(七)

14、ForkJoin ForkJoin框架是Java中用于并行執行任務的框架&#xff0c;特別適合處理可以分解為多個子任務的復雜計算。它基于“分而治之”的思想&#xff0c;將一個大任務分解為多個小任務&#xff0c;這些小任務可以并行執行&#xff0c;最后將結果合并。 ForkJoin框架的核…

第 7 章:綜合回顧與性能優化

本章目標: 系統化地回顧各類外設接口選型原則 深入探討多接口并存時的資源沖突與管理策略 掌握軟硬件協同的性能分析方法,快速定位并消除瓶頸 總結一整套從架構設計到現場調試的最佳實踐與防坑指南 7.1 綜合選型決策矩陣(深度分析) 除了前文的基礎矩陣,這里引入兩個更細化…

交換機的連接方式堆疊和級聯

以下是交換機的堆疊和級聯各自的優缺點總結&#xff0c;幫助快速對比選擇&#xff1a; ?一、堆疊&#xff08;Stacking&#xff09;? ?優點 ?高性能 堆疊鏈路帶寬高&#xff08;如10G/40G/100G&#xff09;&#xff0c;成員間數據通過背板直連&#xff0c;無帶寬瓶頸。支…

C++高效求解非線性方程組的實踐指南

非線性方程組的求解是科學與工程計算中的核心問題之一&#xff0c;涉及物理建模、機器學習、金融分析等多個領域。C因其高性能和底層控制能力成為此類問題的首選語言&#xff0c;但如何高效實現求解仍存在諸多挑戰。本文從算法選擇、工具應用、穩定性優化及性能提升四個維度&am…

2025年- H42-Lc150 --146. LRU緩存(哈希表,雙鏈表)需二刷--Java版

1.題目描述 2.思路 LRU(最近最少使用&#xff09;&#xff1a;如果緩存的容量為2&#xff0c;剛開始的兩個元素都入棧。之后該2元素中有其中一個元素&#xff08;重點元素&#xff09;被訪問。把最近訪問過的重點元素保留&#xff0c;另一個邊緣元素就得離開緩存了。 下面是l…

5G 網絡中 DNN 的深度解析:從基礎概念到核心應用

摘要 本文深度剖析 5G 網絡中 DNN(數據網絡名稱)的核心作用與運行機制,從基礎概念入手,詳細闡述 DNN 在會話管理、用戶面資源分配、切片選擇等方面的關鍵功能。通過實際應用場景分析與技術實現細節探討,揭示 DNN 如何助力 5G 網絡滿足多樣化業務需求,為 5G 網絡部署、優…

MLpack 開源庫介紹與使用指南

MLpack 開源庫介紹與使用指南 1. MLpack 簡介 MLpack 是一個快速、靈活的 C 機器學習庫&#xff0c;專注于可擴展性、速度和易用性。它提供了大量經典的機器學習算法實現&#xff0c;包括&#xff1a; 監督學習&#xff08;分類、回歸&#xff09;無監督學習&#xff08;聚類…