|
@@ -9,6 +9,7 @@ import ai.java.back.service.ChatService;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
|
|
+import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
|
|
|
|
import okhttp3.*;
|
|
import okhttp3.*;
|
|
import org.jetbrains.annotations.NotNull;
|
|
import org.jetbrains.annotations.NotNull;
|
|
@@ -222,7 +223,13 @@ public class ChatServiceImpl implements ChatService {
|
|
}
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
-
|
|
|
|
|
|
+ /**
|
|
|
|
+ * 处理每个数据块
|
|
|
|
+ *
|
|
|
|
+ * @param emitter SseEmitter 对象
|
|
|
|
+ * @param chunk 数据块
|
|
|
|
+ * @throws IOException 处理数据块时发生的异常
|
|
|
|
+ */
|
|
private void processChunk(SseEmitter emitter, OllamaChatResponse chunk) throws IOException {
|
|
private void processChunk(SseEmitter emitter, OllamaChatResponse chunk) throws IOException {
|
|
ChatStreamResponse chatStreamResponse = new ChatStreamResponse();
|
|
ChatStreamResponse chatStreamResponse = new ChatStreamResponse();
|
|
chatStreamResponse.setContent(chunk.getMessage().getContent());
|
|
chatStreamResponse.setContent(chunk.getMessage().getContent());
|
|
@@ -242,4 +249,38 @@ public class ChatServiceImpl implements ChatService {
|
|
throw new RuntimeException(e);
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public String askModel(String question) throws IOException {
|
|
|
|
+ // 构建请求体
|
|
|
|
+ ObjectNode requestBody = objectMapper.createObjectNode();
|
|
|
|
+ requestBody.put("model", "qwen2.5:0.5b");
|
|
|
|
+ requestBody.put("temperature", 0.8);
|
|
|
|
+ requestBody.put("prompt", question);
|
|
|
|
+ requestBody.put("stream", false);
|
|
|
|
+
|
|
|
|
+ Request request = new Request.Builder()
|
|
|
|
+ .url(String.format("http://%s:%d/api/generate", ollamaHost, ollamaPort))
|
|
|
|
+ .post(RequestBody.create(
|
|
|
|
+ objectMapper.writeValueAsString(requestBody),
|
|
|
|
+ MediaType.parse("application/json")
|
|
|
|
+ ))
|
|
|
|
+ .build();
|
|
|
|
+ Response response = client.newCall(request).execute();
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ // 解析响应内容并提取嵌套的 content 字段
|
|
|
|
+ String responseBody = response.body().string();
|
|
|
|
+ System.out.println(responseBody);
|
|
|
|
+ String extractedContent;
|
|
|
|
+ try {
|
|
|
|
+ JsonNode rootNode = objectMapper.readTree(responseBody);
|
|
|
|
+ // 修正为提取 response 字段
|
|
|
|
+ extractedContent = rootNode.path("response").asText();
|
|
|
|
+ } catch (JsonProcessingException e) {
|
|
|
|
+ throw new RuntimeException("Failed to parse response body", e);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ return extractedContent;
|
|
|
|
+ }
|
|
}
|
|
}
|