mirror of
https://gitee.com/lucinox/dsapi_pub.git
synced 2026-12-07 02:55:00 +08:00
193 lines
6.9 KiB
Java
193 lines
6.9 KiB
Java
import java.net.URI;
|
|
import java.net.http.HttpClient;
|
|
import java.net.http.HttpRequest;
|
|
import java.net.http.HttpResponse;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.time.Duration;
|
|
import java.util.Scanner;
|
|
|
|
/**
|
|
* 独立控制台示例:调用 DSapi 对外提供商问答接口 POST /v1/provider/chat
|
|
* <p>
|
|
* 编译:javac ProviderChatDemo.java
|
|
* 运行:java ProviderChatDemo
|
|
* <p>
|
|
* 依赖:仅需 JDK 11+(自带 HttpClient),无需 Spring / Maven。
|
|
*/
|
|
public class ProviderChatDemo {
|
|
|
|
/** 服务地址,按实际修改 */
|
|
private static final String BASE_URL = "http://localhost:8080";
|
|
|
|
/** 你的 API Key(在 DSapi 后台创建),请改成真实值 */
|
|
private static final String API_KEY = "YOUR_API_KEY";
|
|
|
|
/** 是否联网(智能搜索) */
|
|
private static final boolean WEB_SEARCH = false;
|
|
|
|
/** none=每次新对话;save=同一 Key 复用上下文 */
|
|
private static final String HISTORY_MODE = "none";
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
System.out.println("=== DSapi Provider Chat Demo ===");
|
|
System.out.println("URL: " + BASE_URL + "/v1/provider/chat");
|
|
System.out.println("apiKey: " + (API_KEY == null || API_KEY.isBlank() || "YOUR_API_KEY".equals(API_KEY)
|
|
? "(请先改代码里的 API_KEY)" : mask(API_KEY)));
|
|
System.out.println("webSearch=" + WEB_SEARCH + ", historyMode=" + HISTORY_MODE);
|
|
System.out.println("输入问题后回车发送;输入 exit / quit 退出。");
|
|
System.out.println();
|
|
|
|
HttpClient client = HttpClient.newBuilder()
|
|
.connectTimeout(Duration.ofSeconds(15))
|
|
.build();
|
|
|
|
try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) {
|
|
while (true) {
|
|
System.out.print("你> ");
|
|
if (!scanner.hasNextLine()) {
|
|
break;
|
|
}
|
|
String question = scanner.nextLine().trim();
|
|
if (question.isEmpty()) {
|
|
continue;
|
|
}
|
|
if ("exit".equalsIgnoreCase(question) || "quit".equalsIgnoreCase(question)) {
|
|
System.out.println("再见。");
|
|
break;
|
|
}
|
|
|
|
String body = buildJsonBody(API_KEY, question, WEB_SEARCH, HISTORY_MODE);
|
|
HttpRequest request = HttpRequest.newBuilder()
|
|
.uri(URI.create(BASE_URL + "/v1/provider/chat"))
|
|
.timeout(Duration.ofMinutes(5))
|
|
.header("Content-Type", "application/json; charset=UTF-8")
|
|
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
|
|
.build();
|
|
|
|
System.out.println("请求中...");
|
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
|
System.out.println("HTTP " + response.statusCode());
|
|
System.out.println("原始响应:");
|
|
System.out.println(response.body());
|
|
System.out.println();
|
|
|
|
printParsedAnswer(response.body());
|
|
System.out.println();
|
|
}
|
|
}
|
|
}
|
|
|
|
/** 按文档构造 JSON(不依赖第三方库,手工转义) */
|
|
private static String buildJsonBody(String apiKey, String question, boolean webSearch, String historyMode) {
|
|
return "{"
|
|
+ "\"apiKey\":\"" + escapeJson(apiKey) + "\","
|
|
+ "\"question\":\"" + escapeJson(question) + "\","
|
|
+ "\"webSearch\":" + webSearch + ","
|
|
+ "\"historyMode\":\"" + escapeJson(historyMode) + "\""
|
|
+ "}";
|
|
}
|
|
|
|
private static String escapeJson(String s) {
|
|
if (s == null) {
|
|
return "";
|
|
}
|
|
return s.replace("\\", "\\\\")
|
|
.replace("\"", "\\\"")
|
|
.replace("\r", "\\r")
|
|
.replace("\n", "\\n")
|
|
.replace("\t", "\\t");
|
|
}
|
|
|
|
private static String mask(String key) {
|
|
if (key.length() <= 4) {
|
|
return "****";
|
|
}
|
|
return key.substring(0, 2) + "****" + key.substring(key.length() - 2);
|
|
}
|
|
|
|
/** 粗略从 JSON 里抠 answer / code / message,方便黑窗口阅读 */
|
|
private static void printParsedAnswer(String json) {
|
|
if (json == null || json.isBlank()) {
|
|
return;
|
|
}
|
|
String code = extractStringField(json, "code");
|
|
String message = extractStringField(json, "message");
|
|
String answer = extractNestedAnswer(json);
|
|
System.out.println("--- 解析 ---");
|
|
System.out.println("code : " + code);
|
|
System.out.println("message: " + message);
|
|
if (answer != null) {
|
|
System.out.println("answer :");
|
|
System.out.println(answer);
|
|
} else if (!"0".equals(code)) {
|
|
System.out.println("(调用失败,见上方原始响应)");
|
|
}
|
|
}
|
|
|
|
private static String extractStringField(String json, String field) {
|
|
String key = "\"" + field + "\"";
|
|
int i = json.indexOf(key);
|
|
if (i < 0) {
|
|
return null;
|
|
}
|
|
int colon = json.indexOf(':', i + key.length());
|
|
if (colon < 0) {
|
|
return null;
|
|
}
|
|
int start = json.indexOf('"', colon + 1);
|
|
if (start < 0) {
|
|
return null;
|
|
}
|
|
int end = findClosingQuote(json, start + 1);
|
|
if (end < 0) {
|
|
return null;
|
|
}
|
|
return unescapeJson(json.substring(start + 1, end));
|
|
}
|
|
|
|
/** 取 data.answer */
|
|
private static String extractNestedAnswer(String json) {
|
|
int dataIdx = json.indexOf("\"data\"");
|
|
if (dataIdx < 0) {
|
|
return null;
|
|
}
|
|
String fromData = json.substring(dataIdx);
|
|
return extractStringField(fromData, "answer");
|
|
}
|
|
|
|
private static int findClosingQuote(String s, int from) {
|
|
for (int i = from; i < s.length(); i++) {
|
|
char c = s.charAt(i);
|
|
if (c == '\\') {
|
|
i++;
|
|
continue;
|
|
}
|
|
if (c == '"') {
|
|
return i;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
private static String unescapeJson(String s) {
|
|
StringBuilder sb = new StringBuilder();
|
|
for (int i = 0; i < s.length(); i++) {
|
|
char c = s.charAt(i);
|
|
if (c == '\\' && i + 1 < s.length()) {
|
|
char n = s.charAt(++i);
|
|
switch (n) {
|
|
case 'n' -> sb.append('\n');
|
|
case 'r' -> sb.append('\r');
|
|
case 't' -> sb.append('\t');
|
|
case '"' -> sb.append('"');
|
|
case '\\' -> sb.append('\\');
|
|
default -> sb.append(n);
|
|
}
|
|
} else {
|
|
sb.append(c);
|
|
}
|
|
}
|
|
return sb.toString();
|
|
}
|
|
}
|