阿里云百煉平臺創建智能體-上傳文檔

整體思路是:

1創建ram用戶,授權

2上傳文件獲取FileSession

3調用智能體對話,傳入FileSession

接下來每個步驟的細節:
1官方不推薦使用超級管理員用戶獲得accessKeyId和accessKeySecret,所以登錄超級管理員賬號創建ram用戶,給這個用戶授權想用的權限即可
創建ram用戶 可以使用官方概覽這里有個快速開始,我這里只是想開發人員使用key,所以選擇了“創建程序用戶”
在這里插入圖片描述
在這里插入圖片描述
最重要的需要授權
點擊上個頁面上的授權,搜素AliyunBailianFullAccess或AliyunBailianControlFullAccess。然后第二步授予workspace權限授予工作空間權限!這個不要忘否則調用的時候會報“401”

在這里插入圖片描述
在這里插入圖片描述
2上傳文件主要有三個步驟,官方文檔快速開始里面有在線調試和sdk開始。看官網就行。
上傳文檔參數說明
在這里插入圖片描述

api接口調用在線調試
在這里插入圖片描述
注意這個上傳文檔可以使用oss,但是需要是公開的,于是我使用本地文檔上傳,通用寫法。我使用的是java,傳入ossId為文檔id,也可以直接換成本地絕對路徑,就不需要從ossId轉localFilePath了,其中的params 放入按照前面獲取到的數據放入即可,如

` private static Map<String, String> params = new HashMap<>();static {params.put("accessKeyId", " ");params.put("accessKeySecret", " ");params.put("workspaceId", "  ");params.put("apiKey", "sk- ");params.put("appId", " ");`
    public String getFileSession(Long ossId) throws IOException {String localFilePath = "";if (null!=ossId) {Path downloadedPath = null;try {downloadedPath = this.getTempFullFilePath(ossId);if (!StrUtil.isBlankIfStr(downloadedPath)) {String strPath = downloadedPath.toAbsolutePath().toString();localFilePath = strPath;} else {return null;}//上傳bailian文件init(localFilePath);/* 1.上傳文件 *//** 1.1.申請文檔上傳租約 **/StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder().accessKeyId(params.get("accessKeyId")).accessKeySecret(params.get("accessKeySecret")).build());AsyncClient client = AsyncClient.builder().credentialsProvider(provider)configuration rewrite, can set Endpoint, Http request parameters, etc..overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("bailian.cn-beijing.aliyuncs.com")).build();ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = ApplyFileUploadLeaseRequest.builder().categoryType(params.get("CategoryType")).categoryId(params.get("CategoryId") ).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 = new URL(param.getUrl());connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("PUT");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));// 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).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();return fileId;} catch (Exception e) {log.error("處理ossId為 {} 的文件失敗: {}",ossId, e.getMessage(), e);} finally {Path tempDir = null;if (null != downloadedPath) {tempDir = downloadedPath.getParent().toAbsolutePath();}if (null != tempDir) {// 遞歸刪除目錄(包括所有子目錄和文件)Files.walkFileTree(tempDir, new SimpleFileVisitor<Path>() {@Overridepublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {// 刪除文件Files.delete(file);return FileVisitResult.CONTINUE;}@Overridepublic FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {// 刪除空目錄Files.delete(dir);return FileVisitResult.CONTINUE;}});}log.info("臨時目錄已刪除!");}}return localFilePath;}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();}

3調用智能體

        ApplicationParam aiParam = ApplicationParam.builder().apiKey("sk- ").appId(" ")  
//        增量輸出,即后續輸出內容不包含已輸出的內容。實時地逐個讀取這些片段以獲得完整的結果。.incrementalOutput(true).prompt(chatModelDto.getMessage())//可傳入歷史記錄
//            .messages().ragOptions(RagOptions.builder().sessionFileIds(fileSessionList).build()).build();Application application = new Application();ApplicationResult result = application.call(aiParam);String text = result.getOutput().getText();return text;
//流式輸出 createResult可忽略,返回Flux<String>
//        Application application = new Application();
//        Flowable<ApplicationResult> result = application.streamCall(aiParam);
//        Flux<Result> resultFlux = Flux.from(result)
//            .map(applicationResult -> {
//                 String response = applicationResult.getOutput().getText();
//                return createResult(response);
//            });
//        return resultFlux;

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

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

相關文章

剪映里面導入多張照片,p圖后如何再導出多張照片?

剪映普通版本暫時沒發現可以批量導出圖片。這里采用其他方式實現。先整體導出視頻。這里前期要注意設置幀率&#xff0c;一張圖片的時長。 參考一下設置&#xff0c;幀率設置為30&#xff0c;圖片導入時長設置為1s&#xff0c;這樣的話&#xff0c;方便后期把視頻切割為單幀。導…

怎么查看Linux I2C總線掛載了那些設備?

1. 根據系統啟動查看設備樹節點文件&#xff08;系統運行后的&#xff09; 比如&#xff1a;要查看I2C2i2c2: i2cfeaa0000 {compatible "rockchip,rk3588-i2c", "rockchip,rk3399-i2c";reg <0x0 0xfeaa0000 0x0 0x1000>;clocks <&cru CLK_…

bat腳本實現獲取非微軟官方服務列表

Get-CimInstance -ClassName Win32_Service |Where-Object { $_.State -eq Running -and $_.StartMode -ne Disabled } | ForEach-Object {$isMicrosoft $false$signerInfo 無可執行路徑if ($_.PathName) {# 提取可執行文件路徑&#xff08;處理帶引號/參數的路徑&#xff09…

小程序難調的組件

背景。做小程序用到了自定義表單。前后端都是分開寫的&#xff0c;沒有使用web-view。所以要做到功能對稱時間選擇器。需要區分datetime, year, day等類型使用uview組件較方便 <template><view class"u-date-picker" v-if"visible"><view c…

從零構建TransformerP2-新聞分類Demo

歡迎來到啾啾的博客&#x1f431;。 記錄學習點滴。分享工作思考和實用技巧&#xff0c;偶爾也分享一些雜談&#x1f4ac;。 有很多很多不足的地方&#xff0c;歡迎評論交流&#xff0c;感謝您的閱讀和評論&#x1f604;。 目錄引言1 一個完整的Transformer模型2 需要準備的“工…

qt qml實現電話簿 通訊錄

qml實現電話簿&#xff0c;基于github上開源代碼修改而來&#xff0c;增加了搜索和展開&#xff0c;效果如下 代碼如下 #include <QGuiApplication> #include <QQmlApplicationEngine>int main(int argc, char *argv[]) {QCoreApplication::setAttribute(Qt::AA_…

順序表——C語言

順序表實現代碼解析與學習筆記一、順序表基礎概念順序表是線性表的一種順序存儲結構&#xff0c;它使用一段連續的內存空間&#xff08;數組&#xff09;存儲數據元素&#xff0c;通過下標直接訪問元素&#xff0c;具有隨機訪問的特性。其核心特點是&#xff1a;元素在內存中連…

【Oracle篇】Oracle Data Pump遠程備份技術:直接從遠端數據庫備份至本地環境

&#x1f4ab;《博主主頁》&#xff1a;    &#x1f50e; CSDN主頁__奈斯DB    &#x1f50e; IF Club社區主頁__奈斯、 &#x1f525;《擅長領域》&#xff1a;擅長阿里云AnalyticDB for MySQL(分布式數據倉庫)、Oracle、MySQL、Linux、prometheus監控&#xff1b;并對…

Linux系統--文件系統

大家好&#xff0c;我們今天繼續來學習Linux系統部分。上一次我們學習了內存級的文件&#xff0c;下面我們來學習磁盤級的文件。那么話不多說&#xff0c;我們開始今天的學習&#xff1a; 目錄 Ext系列?件系統 1. 理解硬件 1-1 磁盤、服務器、機柜、機房 1-2 磁盤物理結構…

KUKA庫卡焊接機器人氬氣節氣設備

在焊接生產過程中&#xff0c;氬氣作為一種重要的保護氣體被廣泛應用于KUKA庫卡焊接機器人的焊接操作中。氬氣的消耗往往是企業生產成本的一個重要組成部分&#xff0c;因此實現庫卡焊接機器人節氣具有重要的經濟和環保意義。WGFACS節氣裝置的出現為解決這一問題提供了有效的方…

遠程連接----ubuntu ,rocky 等Linux系統,WindTerm_2.7.0

新一代開源免費的終端工具-WindTerm github 27.5k? https://github.com/kingToolbox/WindTerm/releases/download/2.7.0/WindTerm_2.7.0_Windows_Portable_x86_64.zip 主機填寫你自己要連接的主機ip 端口默認 22 改成你ssh文件配置的端口 輸入遠程的 用戶名 與密碼 成功連接…

筆試——Day32

文章目錄第一題題目思路代碼第二題題目&#xff1a;思路代碼第三題題目&#xff1a;思路代碼第一題 題目 素數回文 思路 模擬 構建新的數字&#xff0c;判斷該數是否為素數 代碼 第二題 題目&#xff1a; 活動安排 思路 區間問題的貪?&#xff1a;排序&#xff0c;然…

超高車輛如何影響城市立交隧道安全?預警系統如何應對?

超高車輛對立交隧道安全的潛在威脅在城市立交和隧道中&#xff0c;限高設施的設計通常考慮到大部分正常通行的貨車和運輸車輛。然而&#xff0c;一些超高的貨車、集裝箱車或特殊車輛如果未經有效監測而進入限高區域&#xff0c;就可能對道路設施造成極大的安全隱患。尤其在立交…

解決 MinIO 上傳文件時報 S3 API Requests must be made to API port錯誤

在使用 MinIO 進行文件上傳時&#xff0c;我遇到了一個比較坑的問題。錯誤日志如下&#xff1a; io.minio.errors.InvalidResponseException: Non-XML response from server. Response code: 400, Content-Type: text/xml; charsetutf-8, body: <?xml version"1.0&quo…

linux_https,udp,tcp協議(更新中)

目錄 https 加密類型 對稱加密 非對稱加密 加密方案 只用對程加密 只用非對程加密 雙方都是用非對程加密 非對稱對稱加密 非對稱對稱加密證書 流程圖 校驗流程圖 udp udp協議格式 特點 UDP緩沖區 tcp tcp協議格式 32位序號及確認序號 4位首部 6位標志位 1…

web端-登錄頁面驗證碼的實現(springboot+vue前后端分離)超詳細

目錄 一、項目技術棧 二、實現效果圖 ?三、實現路線 四、驗證碼的實現步驟 五、完整代碼 1.前端 2.后端 一、項目技術棧 登錄頁面暫時涉及到的技術棧如下: 前端 Vue2 Element UI Axios&#xff0c;后端 Spring Boot 2 MyBatis MySQL JWT Maven 二、實現效果圖…

瘋狂星期四文案網第33天運營日記

網站運營第33天&#xff0c;點擊觀站&#xff1a; 瘋狂星期四 crazy-thursday.com 全網最全的瘋狂星期四文案網站 運營報告 今日訪問量 今日搜索引擎收錄情況 必應收錄239個頁面&#xff0c;還在持續增加中&#xff0c;已經獲得必應的認可&#xff0c;逐漸收錄所有頁面 百度…

客戶端利用MinIO對服務器數據進行同步

MinIO 是一款高性能、開源的對象存儲服務&#xff0c;專為海量數據存儲設計&#xff0c;兼容 Amazon S3 API&#xff08;即與 AWS S3 協議兼容&#xff09;&#xff0c;可用于構建私有云存儲、企業級數據湖、備份歸檔系統等場景。它以輕量、靈活、高效為核心特點&#xff0c;廣…

WPF 雙擊行為實現詳解:DoubleClickBehavior 源碼分析與實戰指南

WPF 雙擊行為實現詳解:DoubleClickBehavior 源碼分析與實戰指南 文章目錄 WPF 雙擊行為實現詳解:DoubleClickBehavior 源碼分析與實戰指南 引言 一、行為(Behavior)基礎概念 1.1 什么是行為? 1.2 行為的優勢 二、DoubleClickBehavior 源碼分析 2.1 類定義與依賴屬性 2.2 雙…

零知開源——基于STM32F103RBT6的TDS水質監測儀數據校準和ST7789顯示實戰教程

?零知開源是一個真正屬于國人自己的開源軟硬件平臺&#xff0c;在開發效率上超越了Arduino平臺并且更加容易上手&#xff0c;大大降低了開發難度。零知開源在軟件方面提供了完整的學習教程和豐富示例代碼&#xff0c;讓不懂程序的工程師也能非常輕而易舉的搭建電路來創作產品&…