fix:修改适配前端传token值#183
Conversation
WalkthroughThe changes introduce a new enumeration value for foundation models and update the configuration and client handling for AI chat services. Modifications include hardcoding API URLs, adjusting method and constructor signatures to accept a model and token, and updating error and response handling. Additionally, flexible constructors were added to the DTO class, and related test cases were updated to align with the new parameterized approach. Changes
Sequence Diagram(s)sequenceDiagram
participant C as Client
participant AIC as AiChatClient
participant Config as AiChatConfig
participant Service as AiChatServiceImpl
participant AI as External AI API
C->>AIC: Initialize with model & token
AIC->>Config: getAiChatConfig(model, token)
Config-->>AIC: Return configuration data
AIC->>Service: executeChatRequest(AiParam with model & messages)
Service->>Service: Validate token & set foundationModel map
Service->>AI: Request answer using provided configuration
AI-->>Service: Return response/error
Service-->>AIC: Send result back
AIC-->>C: Return chat answer or error
Suggested reviewers
Poem
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
base/src/main/java/com/tinyengine/it/gateway/ai/AiChatClient.java (1)
60-64: Add null checks and refine error handling.
AccessingopenAiBodyDto.getFoundationModel().get("model")directly could lead toNullPointerExceptioniffoundationModelis null or missing the"model"key. Also, returning an empty map on line 64 might obscure the error from the caller; consider throwing an exception or returning an error response.base/src/main/java/com/tinyengine/it/config/AiChatConfig.java (2)
26-28: Consider externalizing hard-coded endpoints.
Hard-coding these URLs limits flexibility for different environments. Storing them in configuration files or environment variables can improve maintainability and facilitate environment-specific overrides.
55-59: Handle null tokens for Ernie Bot.
Appending anulltoken to the URL results in an invalid endpoint. Consider validating the token before constructing the URL or indicating an error if it’s missing.base/src/main/java/com/tinyengine/it/model/dto/AiParam.java (1)
35-37: Consider default field initialization.
If you foresee typical defaults forfoundationModelormessages, you might initialize them in the no-args constructor to prevent null references.base/src/test/java/com/tinyengine/it/service/app/impl/AiChatServiceImplTest.java (1)
72-72: Replace hardcoded token with a constant or test configuration.Using a hardcoded token value "asdf" is not a good practice. Consider:
- Moving it to a test configuration file
- Using a meaningful constant name
-foundationModel.put("token","asdf"); +private static final String TEST_TOKEN = "test_token_value"; +foundationModel.put("token", TEST_TOKEN);base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java (1)
168-168: Consider using dependency injection for AiChatClient.Creating a new client instance for each request is not optimal. Consider:
- Using dependency injection
- Implementing a client pool
- Adding client lifecycle management
-AiChatClient aiChatClient = new AiChatClient(foundationModel.get("model"), foundationModel.get("token")); +@Autowired +private AiChatClientFactory aiChatClientFactory; + +// In method: +AiChatClient aiChatClient = aiChatClientFactory.getClient(foundationModel.get("model"), foundationModel.get("token"));base/src/main/java/com/tinyengine/it/common/enums/Enums.java (1)
791-796: Enhance documentation for the new foundation model.The documentation for MOONSHOT_V1_8K could be more descriptive:
- Add version compatibility information
- Include token requirements
- Document any model-specific limitations
/** - * Moonshot v1 8k e foundation model. + * Moonshot v1 8k foundation model. + * Version: v1 + * Context window: 8k tokens + * Provider: Moonshot AI + * Token requirement: Bearer token required + * @since 2024-02 */ // kimi MOONSHOT_V1_8K("moonshot-v1-8k");
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
base/src/main/java/com/tinyengine/it/common/enums/Enums.java(1 hunks)base/src/main/java/com/tinyengine/it/config/AiChatConfig.java(2 hunks)base/src/main/java/com/tinyengine/it/gateway/ai/AiChatClient.java(3 hunks)base/src/main/java/com/tinyengine/it/model/dto/AiParam.java(1 hunks)base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java(4 hunks)base/src/test/java/com/tinyengine/it/controller/AiChatControllerTest.java(2 hunks)base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java(2 hunks)base/src/test/java/com/tinyengine/it/service/app/impl/AiChatServiceImplTest.java(2 hunks)
✅ Files skipped from review due to trivial changes (1)
- base/src/test/java/com/tinyengine/it/controller/AiChatControllerTest.java
🔇 Additional comments (4)
base/src/main/java/com/tinyengine/it/gateway/ai/AiChatClient.java (2)
20-23: Imports look correct.
These imports forEnumsandAiParamappear consistent with the new functionality.
48-49: Validate null or empty inputs for model/token.
Ifmodelortokenis null/empty, subsequent methods may encounter problems (e.g., missing config). Consider adding safeguards or throwing an exception to handle invalid inputs.base/src/main/java/com/tinyengine/it/config/AiChatConfig.java (1)
35-45: Ensure token usage for recognized models only.
Currently, tokens become"Bearer null"when themodeldoesn't match. This could lead to downstream auth failures. Consider throwing an exception if an unsupported model is specified, or define a fallback logic.base/src/main/java/com/tinyengine/it/model/dto/AiParam.java (1)
29-33: New constructor increases flexibility.
This constructor streamlines object creation with specified model data and messages.
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java
Outdated
Show resolved
Hide resolved
base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java (1)
79-81:⚠️ Potential issueFix token validation logic to prevent NullPointerException.
The current validation is incorrect as it checks
isEmpty()before checking for null, which could cause a NullPointerException.-if(aiParam.getFoundationModel().get("token").isEmpty() || aiParam.getFoundationModel().get("token") == null){ +String token = aiParam.getFoundationModel().get("token"); +if (token == null || token.isEmpty()) { return Result.failed("The token cannot be empty"); }
🧹 Nitpick comments (3)
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java (1)
90-93: Improve test data setup with realistic values.The foundation model setup could be improved:
- Use a constant or meaningful test token instead of "asdf"
- Consider adding test cases for different token scenarios
HashMap<String, String> foundationModel = new HashMap<>(); foundationModel.put("model", "ERNIE-4.0-8K"); -foundationModel.put("token","asdf"); +private static final String TEST_TOKEN = "test_token_12345"; +foundationModel.put("token", TEST_TOKEN);base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java (2)
171-174: Enhance error handling robustness.The error handling could be improved to handle all edge cases:
- Add null checks before toString() calls
- Consider using Optional to handle potential nulls
- Add logging for error scenarios
- String code = response.get("error_code").toString(); - String message = response.get("error_msg").toString(); - return Result.failed(code,message); + String code = Optional.ofNullable(response.get("error_code")) + .map(Object::toString) + .orElse("UNKNOWN_ERROR"); + String message = Optional.ofNullable(response.get("error_msg")) + .map(Object::toString) + .orElse("Unknown error occurred"); + log.error("AI service error: code={}, message={}", code, message); + return Result.failed(code, message);
180-182: Make model result conversion more flexible.The current implementation:
- Only handles ERNIBOT_TURBO specifically
- Uses hard-coded values for role and name
- Lacks extensibility for future models
Consider implementing a more flexible conversion strategy.
- if (Enums.FoundationModel.ERNIBOT_TURBO.getValue().equals(foundationModel.get("model"))) { - return modelResultConvet(response); - } + return Optional.ofNullable(foundationModel.get("model")) + .map(model -> { + if (Enums.FoundationModel.ERNIBOT_TURBO.getValue().equals(model)) { + return modelResultConvet(response); + } + // Add support for other models here + return Result.success(response); + }) + .orElse(Result.failed("Model not specified"));
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java(3 hunks)base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java(4 hunks)
🔇 Additional comments (1)
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java (1)
95-95:Details
❓ Verification inconclusive
Consider encoding issues with test data.
The test content contains Chinese characters which might cause encoding issues in different environments. Consider using Unicode escape sequences or moving the test data to a separate resource file.
🏁 Script executed:
#!/bin/bash # Check if the file uses UTF-8 encoding file base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.javaLength of output: 171
Encoding Verification: Manual Check Required
The command to check the file’s encoding did not produce valid output due to the unavailability of the
filecommand in this environment. Since the test data inbase/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.javaat line 95 contains Chinese characters, please verify manually that the file uses UTF-8 or consider converting the test string to Unicode escape sequences or relocating it to a dedicated resource file to avoid potential environment-specific encoding issues.
- Location to review:
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java(line 95)
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java (3)
90-90: Replace hardcoded token with a constant or test configuration.Using hardcoded credentials in test code is not a good practice. Consider:
- Moving the token to a test configuration file
- Using a constant with a clear name like
TEST_TOKEN- Using a mock token generator
- foundationModel.put("token","asdf"); + foundationModel.put("token", TEST_TOKEN);
93-96: Document test data containing non-ASCII characters.Add a comment explaining the purpose and expected behavior of the Chinese characters in the test data. This helps other developers understand the test case's intent.
+ // Test case with Chinese characters to verify Unicode support aiMessages.setContent("dddd编码时遵从以下几条要求aaa"); aiMessages.setName("John"); aiMessages.setRole("user");
105-106: Maintain consistency in test data.The model name differs from the one used in
testExecuteChatRequest. Consider using a constant for the model name to maintain consistency across tests.+ private static final String TEST_MODEL = "ERNIE-4.0-8K"; + @Test void testInvalidTokenExecuteChatRequest() { HashMap<String, String> foundationModel = new HashMap<>(); - foundationModel.put("model", "gpt-3.5-turbo"); + foundationModel.put("model", TEST_MODEL); foundationModel.put("token","你好");
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java(3 hunks)base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java
🔇 Additional comments (2)
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java (2)
99-99: Enhance test assertions.The current assertion only checks if the data is null. Consider adding more comprehensive assertions to verify:
- The complete response structure
- The presence of required fields
- The format of the response
- Assertions.assertNull(returnData.get("data")); + Assertions.assertNotNull(returnData, "Response should not be null"); + Assertions.assertTrue(returnData.containsKey("data"), "Response should contain 'data' key"); + Assertions.assertTrue(returnData.containsKey("choices"), "Response should contain 'choices' key");
102-114: Add test cases for token validation.The test should include scenarios for:
- Invalid/empty tokens
- Token validation failures
- Different model configurations
Add these test cases:
Map<String,String> map = new HashMap<>(); map.put("model",modelName); +map.put("token", "valid_token"); AiMessages aiMessages = new AiMessages(); AiParam param = new AiParam(map,Arrays.asList(aiMessages)); +// Test invalid token +Map<String,String> invalidMap = new HashMap<>(); +invalidMap.put("model", modelName); +invalidMap.put("token", ""); +AiParam invalidParam = new AiParam(invalidMap, Arrays.asList(aiMessages)); +// Test token validation failure +when(aiChatClient.executeChatRequest(invalidParam)) + .thenThrow(new IllegalArgumentException("Invalid token"));
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
base/src/main/java/com/tinyengine/it/controller/PageHistoryController.java (1)
169-191: LGTM! Well-structured endpoint with comprehensive documentation.The new endpoint is well-implemented with:
- Clear OpenAPI documentation
- Proper parameter validation
- Consistent error handling through Result wrapper
- Follows the established controller patterns
However, consider adding input validation for the
nameparameter to prevent potential injection attacks or invalid inputs.@GetMapping("/pages/histories/find") public Result<List<PageHistory>> findPageHistory(@RequestParam("name") String name, @RequestParam Integer app) { + if (name == null || name.trim().isEmpty()) { + return Result.failed("Name parameter cannot be empty"); + } + // Optional: Add pattern validation if there are specific naming rules + if (!Pattern.matches("^[a-zA-Z0-9-_]+$", name)) { + return Result.failed("Invalid name format"); + } List<PageHistory> pageHistoryList = pageHistoryService.findPageHistoryByName(name, app); return Result.success(pageHistoryList); }
* feat: add doc * modify doc * fix:modify adapt nodejs to java create app * fix:fix doc * fix:fix h2 script * fix:fix the official website document link * fix:fix AI token * fix:modify ai token * fix:fix Ai token * fix:fix issues * fix:fix issues * fix:modify comment
* fix:修改适配前端传token值 (#183) * feat: add doc * modify doc * fix:modify adapt nodejs to java create app * fix:fix doc * fix:fix h2 script * fix:fix the official website document link * fix:fix AI token * fix:modify ai token * fix:fix Ai token * fix:fix issues * fix:fix issues * fix:modify comment * feat: add npmrc info to component schema info --------- Co-authored-by: zhangjuncao <163953928+zhangjuncao@users.noreply.github.com>
* feat: add doc * modify doc * fix:modify adapt nodejs to java create app * fix:fix doc * fix:fix h2 script * fix:fix the official website document link * fix:fix AI token * fix:modify ai token * fix:fix Ai token * fix:fix issues * fix:fix issues * fix:modify comment
* fix:修改适配前端传token值 (opentiny#183) * feat: add doc * modify doc * fix:modify adapt nodejs to java create app * fix:fix doc * fix:fix h2 script * fix:fix the official website document link * fix:fix AI token * fix:modify ai token * fix:fix Ai token * fix:fix issues * fix:fix issues * fix:modify comment * feat: add npmrc info to component schema info --------- Co-authored-by: zhangjuncao <163953928+zhangjuncao@users.noreply.github.com>
English | 简体中文
PR
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
Background and solution
What is the current behavior?
Issue Number: N/A
What is the new behavior?
Does this PR introduce a breaking change?
Other information
Summary by CodeRabbit