RuoYi框架-工具类调用fastGPT知识库上传/删除接口

RuYi框架-调用fastGPT知识库上传/删除接口

package com.ruoyi.knowledge.tools;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.knowledge.constant.KnowledgeConstants;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * fastGPT工具嘞
 *
 * @author sky
 * @date 2025-04-24
 */
@Component
public class FastGptTool {
	public String getFastGptToken() {
		RestTemplate restTemplate = new RestTemplate();
		String url = "https://agent.geyuandiaoyan.com/api/support/user/account/loginByPassword";

		// 构造请求体
		Map<String, String> requestBody = new HashMap<>();
		requestBody.put("username", "root");
		requestBody.put("password", "edbba7268fc1543b4a72a0cabaf7dc617f6cf8fdef02b5814b731b835911e10d");

		// 设置请求头
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);

		// 发送请求
		HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
		ResponseEntity<Map> response = restTemplate.postForEntity(url, requestEntity, Map.class);

		// 从响应中的data字段获取token
		if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
			Map<String, Object> responseBody = response.getBody();
			if (responseBody.containsKey("data")) {
				Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
				return (String) data.get("token");
			}
		}
		throw new RuntimeException("获取FastGPT token失败");
	}

	/**
	 * 删除数据集
	 *
	 * @param apiKey     认证token
	 * @param datasetId  数据集ID
	 * @param searchText 搜索文本
	 * @return 数据集列表
	 */
	public JSONArray getDatasetCollections(String apiKey, String datasetId, String searchText) {
		RestTemplate restTemplate = new RestTemplate();
		String url = "https://agent.geyuandiaoyan.com/api/core/dataset/collection/listV2";

		try {
			// Verify token is valid
			if (apiKey == null || apiKey.isEmpty()) {
				throw new RuntimeException("Invalid or missing authentication apiKey");
			}

			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.set("Authorization", "Bearer " + apiKey);

			Map<String, Object> requestBody = new HashMap<>();
			requestBody.put("offset", 0);
			requestBody.put("pageSize", 10);
			requestBody.put("datasetId", datasetId);
			requestBody.put("parentId", null);
			requestBody.put("searchText", searchText);

			HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
			ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

			if (response.getStatusCode() == HttpStatus.OK) {

				JSONObject jsonObject = JSON.parseObject(response.getBody());
				return jsonObject.getJSONObject("data").getJSONArray("list");
			} else {
				throw new RuntimeException("API request failed with status: " +
						response.getStatusCode() + " - " + response.getBody());
			}
		} catch (HttpClientErrorException e) {
			throw new RuntimeException("Authentication failed: " + e.getResponseBodyAsString(), e);
		} catch (HttpServerErrorException e) {
			throw new RuntimeException("Server error: " + e.getResponseBodyAsString(), e);
		}
	}

	/**
	 * 查看数据集详情
	 *
	 * @param knowledgeId 删除id值
	 * @param apiKey
	 * @return 删除结果
	 */
	public String getDatasetCollectionDetail(String apiKey, String knowledgeId) {
		RestTemplate restTemplate = new RestTemplate();
		try {
			// 设置请求头
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.set("Authorization", "Bearer " + apiKey);
			// 构建请求URL
			String url = "https://agent.geyuandiaoyan.com/api/core/dataset/collection/detail?id=" + knowledgeId;
			// 创建请求实体
			HttpEntity<String> requestEntity = new HttpEntity<>(headers);

			// 发送GET请求
			ResponseEntity<String> response = restTemplate.exchange(
					url,
					HttpMethod.GET,
					requestEntity,
					String.class
			);

			// 检查响应状态码
			if (response.getStatusCode() == HttpStatus.OK) {
				return response.getBody();
			} else {
				throw new RuntimeException("FastGPT接口调用失败,状态码: " + response.getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException("调用FastGPT获取详情接口异常: " + e.getMessage(), e);
		}
	}


	/**
	 * 获取数据集集合列表
	 *
	 * @param knowledgeId 删除id值
	 * @param apiKey
	 * @return 删除结果
	 */
	public String deleteDatasetCollection(String apiKey, String knowledgeId) {
		RestTemplate restTemplate = new RestTemplate();
		try {
			// 设置请求头
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			headers.set("Authorization", "Bearer " + apiKey);
			// 构建请求URL
			String url = "https://agent.geyuandiaoyan.com/api/core/dataset/collection/delete?id=" + knowledgeId;
			// 创建请求实体
			HttpEntity<String> requestEntity = new HttpEntity<>(headers);

			// 发送DELETE请求
			ResponseEntity<String> response = restTemplate.exchange(
					url,
					HttpMethod.DELETE,
					requestEntity,
					String.class
			);

			// 检查响应状态码
			if (response.getStatusCode() == HttpStatus.OK) {
				return response.getBody();
			} else {
				throw new RuntimeException("FastGPT接口调用失败,状态码: " + response.getStatusCode());
			}
		} catch (Exception e) {
			throw new RuntimeException("调用FastGPT删除接口异常: " + e.getMessage(), e);
		}
	}

	/**
	 * 上传本地文件到FastGPT知识库
	 *
	 * @param apiKey   FastGPT API密钥
	 * @param filePath 本地文件路径
	 * @return API响应结果
	 */
	public String uploadLocalFile(String apiKey, String filePath) {
		try {
			// 构建请求URL
			String url = "https://agent.geyuandiaoyan.com/api/core/dataset/collection/create/localFile";

			// 构建JSON参数
			JSONObject params = new JSONObject();
			params.put("datasetId", "68072be7f2a351d24a04739d"); // 默认知识库ID
			params.put("parentId", null);
			params.put("trainingType", "chunk");
			params.put("chunkSize", 512);
			params.put("chunkSplitter", "");
			params.put("qaPrompt", "");
			params.put("metadata", new JSONObject());

			// 创建多部分请求体
			MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();

			// 处理文件路径和编码
			File file = new File(filePath);
			if (!file.exists()) {
				throw new ServiceException("文件不存在: " + filePath);
			}

			// 处理中文文件名编码
			String encodedFilename = URLEncoder.encode(file.getName(), "UTF-8")
					.replaceAll("\\+", "%20");

			// 创建自定义Resource处理文件名
			FileSystemResource resource = new FileSystemResource(file) {
				@Override
				public String getFilename() {
					return encodedFilename;
				}
			};

			body.add("file", resource);
			body.add("data", params.toJSONString());

			// 设置请求头
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.MULTIPART_FORM_DATA);
			headers.set("Authorization", "Bearer " + apiKey);

			// 创建请求实体
			HttpEntity<MultiValueMap<String, Object>> requestEntity =
					new HttpEntity<>(body, headers);

			// 创建并配置RestTemplate
			RestTemplate restTemplate = new RestTemplate();
			restTemplate.getMessageConverters()
					.add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

			// 发送请求并获取响应
			ResponseEntity<String> response = restTemplate.exchange(
					url, HttpMethod.POST, requestEntity, String.class);

			return response.getBody();
		} catch (Exception e) {
//            log.error("上传文件到FastGPT失败", e);
			throw new ServiceException("上传文件到FastGPT失败: " + e.getMessage());
		}
	}

}
posted @ 2025-05-09 08:02  skystrivegao  阅读(117)  评论(0)    收藏  举报