-
Notifications
You must be signed in to change notification settings - Fork 52
feat: Add a universal OpenAI API #251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
262db02
feat: add docker-compose file
lu-yg a6bab59
feat: add maven settings.xml
lu-yg 5ed6d4e
feat: add docker deploy
lu-yg 7253d72
feat: add dockerfile
lu-yg 8adea2a
add docker deploy
lu-yg 3d418bf
add docker deploy
lu-yg 987512d
feat: add docker deploy
lu-yg a9ad907
fix: fix application-alpha.yml
lu-yg 899816f
fix: Fix nginx.conf
lu-yg 2b9768d
fix: Fix init_data_for_test_v1.0.0.sql
lu-yg f190b6f
fix: fix init_data_for_test_v1.0.0.sql
lu-yg 797ba7a
fix: fix init_data_for_test_v1.0.0.sql
lu-yg 7e668bf
feat: Add a universal OpenAI API
lu-yg dac0490
Merge branch 'opentiny:develop' into feat/docker
lu-yg 61b73ee
Merge branch 'feat/docker' of github.com:lu-yg/tiny-engine-backend-ja…
lu-yg 75d535e
feat: Add a universal OpenAI API
lu-yg 55af856
feat: Add a universal OpenAI API
lu-yg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
base/src/main/java/com/tinyengine/it/common/converter/StreamingResponseBodyConverter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/** | ||
* Copyright (c) 2023 - present TinyEngine Authors. | ||
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd. | ||
* | ||
* Use of this source code is governed by an MIT-style license. | ||
* | ||
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, | ||
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR | ||
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS. | ||
* | ||
*/ | ||
|
||
package com.tinyengine.it.common.converter; | ||
|
||
|
||
import org.springframework.http.HttpInputMessage; | ||
import org.springframework.http.HttpOutputMessage; | ||
import org.springframework.http.MediaType; | ||
import org.springframework.http.converter.AbstractHttpMessageConverter; | ||
import org.springframework.http.converter.HttpMessageNotReadableException; | ||
import org.springframework.http.converter.HttpMessageNotWritableException; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; | ||
|
||
import java.io.IOException; | ||
import java.io.OutputStream; | ||
|
||
/** | ||
* The type StreamingResponseBodyConverter. | ||
* | ||
* @since 2025-08-06 | ||
*/ | ||
@Component | ||
public class StreamingResponseBodyConverter extends AbstractHttpMessageConverter<StreamingResponseBody> { | ||
|
||
public StreamingResponseBodyConverter() { | ||
super(MediaType.TEXT_EVENT_STREAM); | ||
} | ||
|
||
@Override | ||
protected boolean supports(Class<?> clazz) { | ||
return StreamingResponseBody.class.isAssignableFrom(clazz); | ||
} | ||
|
||
@Override | ||
protected StreamingResponseBody readInternal(Class<? extends StreamingResponseBody> clazz, HttpInputMessage inputMessage) | ||
throws IOException, HttpMessageNotReadableException { | ||
throw new UnsupportedOperationException("Streaming response body does not support input."); | ||
} | ||
|
||
@Override | ||
protected void writeInternal(StreamingResponseBody responseBody, HttpOutputMessage outputMessage) | ||
throws IOException, HttpMessageNotWritableException { | ||
OutputStream outputStream = outputMessage.getBody(); | ||
responseBody.writeTo(outputStream); // 使用 StreamingResponseBody 的 writeTo 方法 | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
base/src/main/java/com/tinyengine/it/config/OpenAIConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
/** | ||
* Copyright (c) 2023 - present TinyEngine Authors. | ||
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd. | ||
* | ||
* Use of this source code is governed by an MIT-style license. | ||
* | ||
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, | ||
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR | ||
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS. | ||
* | ||
*/ | ||
|
||
package com.tinyengine.it.config; | ||
|
||
import lombok.Data; | ||
import org.springframework.context.annotation.Configuration; | ||
|
||
/** | ||
* The type Open AI config. | ||
* | ||
* @since 2025-08-06 | ||
*/ | ||
@Data | ||
@Configuration | ||
public class OpenAIConfig { | ||
private String apiKey = "your-api-key"; | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private String baseUrl = "https://api.deepseek.com/chat/completions"; | ||
private String defaultModel = "deepseek-chat"; | ||
private int timeoutSeconds = 300; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
base/src/main/java/com/tinyengine/it/model/dto/ChatRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/** | ||
* Copyright (c) 2023 - present TinyEngine Authors. | ||
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd. | ||
* | ||
* Use of this source code is governed by an MIT-style license. | ||
* | ||
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, | ||
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR | ||
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS. | ||
* | ||
*/ | ||
|
||
package com.tinyengine.it.model.dto; | ||
|
||
import lombok.Data; | ||
|
||
import java.util.List; | ||
|
||
/** | ||
* ChatRequest dto | ||
* | ||
* @since 2025-08-06 | ||
*/ | ||
@Data | ||
public class ChatRequest { | ||
private String model; | ||
private String apiKey; | ||
private String baseUrl; | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private List<AiMessages> messages; | ||
private Double temperature = 0.7; | ||
private boolean stream = false; // 流式开关 | ||
} | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
133 changes: 133 additions & 0 deletions
133
base/src/main/java/com/tinyengine/it/service/app/impl/v1/AiChatV1ServiceImpl.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
/** | ||
* Copyright (c) 2023 - present TinyEngine Authors. | ||
* Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd. | ||
* | ||
* Use of this source code is governed by an MIT-style license. | ||
* | ||
* THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, | ||
* BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR | ||
* A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS. | ||
* | ||
*/ | ||
|
||
package com.tinyengine.it.service.app.impl.v1; | ||
|
||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.JsonNode; | ||
import com.tinyengine.it.common.exception.ExceptionEnum; | ||
import com.tinyengine.it.common.exception.ServiceException; | ||
import com.tinyengine.it.common.utils.JsonUtils; | ||
import com.tinyengine.it.config.OpenAIConfig; | ||
import com.tinyengine.it.model.dto.ChatRequest; | ||
import com.tinyengine.it.service.app.v1.AiChatV1Service; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; | ||
|
||
import java.io.IOException; | ||
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.HashMap; | ||
import java.util.Map; | ||
import java.util.stream.Stream; | ||
|
||
/** | ||
* The type AiChat v1 service. | ||
* | ||
* @since 2025-08-06 | ||
*/ | ||
@Service | ||
@Slf4j | ||
public class AiChatV1ServiceImpl implements AiChatV1Service { | ||
private final OpenAIConfig config = new OpenAIConfig(); | ||
private HttpClient httpClient = HttpClient.newBuilder() | ||
.connectTimeout(Duration.ofSeconds(config.getTimeoutSeconds())) | ||
.build(); | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* chatCompletion. | ||
* | ||
* @param request the request | ||
* @return Object the Object | ||
*/ | ||
@Override | ||
public Object chatCompletion(ChatRequest request) throws Exception { | ||
String requestBody = buildRequestBody(request); | ||
String apiKey = request.getApiKey() != null ? request.getApiKey() : config.getApiKey(); | ||
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder() | ||
.uri(URI.create(request.getBaseUrl() != null ? request.getBaseUrl() : config.getBaseUrl())) | ||
.header("Content-Type", "application/json") | ||
.header("Authorization", "Bearer " + apiKey) | ||
.POST(HttpRequest.BodyPublishers.ofString(requestBody)); | ||
|
||
if (request.isStream()) { | ||
requestBuilder.header("Accept", "text/event-stream"); | ||
return processStreamResponse(requestBuilder); | ||
} else { | ||
return processStandardResponse(requestBuilder); | ||
} | ||
} | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
private String buildRequestBody(ChatRequest request) throws JsonProcessingException { | ||
Map<String, Object> body = new HashMap<>(); | ||
body.put("model", request.getModel() != null ? request.getModel() : config.getDefaultModel()); | ||
body.put("messages", request.getMessages()); | ||
body.put("temperature", request.getTemperature()); | ||
body.put("stream", request.isStream()); | ||
|
||
return JsonUtils.encode(body); | ||
} | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
private JsonNode processStandardResponse(HttpRequest.Builder requestBuilder) | ||
throws Exception { | ||
HttpResponse<String> response = httpClient.send( | ||
requestBuilder.build(), HttpResponse.BodyHandlers.ofString()); | ||
return JsonUtils.MAPPER.readTree(response.body()); | ||
} | ||
|
||
private StreamingResponseBody processStreamResponse(HttpRequest.Builder requestBuilder) { | ||
return outputStream -> { | ||
try { | ||
HttpResponse<Stream<String>> response = httpClient.send( | ||
requestBuilder.build(), HttpResponse.BodyHandlers.ofLines()); | ||
try (Stream<String> lines = response.body()) { | ||
lines.filter(line -> !line.isEmpty()) | ||
.forEach(line -> { | ||
try { | ||
if (!line.startsWith("data:")) { | ||
line = "data: " + line; | ||
} | ||
if (!line.endsWith("\n\n")) { | ||
line = line + "\n\n"; | ||
} | ||
outputStream.write(line.getBytes(StandardCharsets.UTF_8)); | ||
outputStream.flush(); | ||
} catch (IOException e) { | ||
throw new ServiceException(ExceptionEnum.CM326.getResultCode(), | ||
ExceptionEnum.CM326.getResultMsg()); | ||
} | ||
}); | ||
} | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} catch (Exception e) { | ||
try { | ||
String errorEvent = "data: " + | ||
JsonUtils.encode(Map.of("error", e.getMessage())) + "\n\n"; | ||
outputStream.write(errorEvent.getBytes(StandardCharsets.UTF_8)); | ||
outputStream.flush(); | ||
} catch (IOException ioException) { | ||
throw new ServiceException(ExceptionEnum.CM326.getResultCode(), ExceptionEnum.CM326.getResultMsg()); | ||
} | ||
} finally { | ||
try { | ||
outputStream.close(); | ||
} catch (IOException e) { | ||
// 忽略关闭异常 | ||
} | ||
} | ||
}; | ||
lu-yg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.