整體思路是:
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;