Skip to content

fix:修改适配前端传token值#183

Merged
lu-yg merged 18 commits intoopentiny:developfrom
zhangjuncao:develop
Feb 21, 2025
Merged

fix:修改适配前端传token值#183
lu-yg merged 18 commits intoopentiny:developfrom
zhangjuncao:develop

Conversation

@zhangjuncao
Copy link
Collaborator

@zhangjuncao zhangjuncao commented Feb 14, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features
    • Expanded available foundation models by adding a new, high-resolution option.
  • Refactor
    • Updated API configurations to now require explicit model and token inputs, improving overall reliability.
    • Enhanced error validation during AI chat interactions for more robust responses.
    • Changed method functionality from deleting page history to retrieving it based on specified criteria.
  • Tests
    • Revised test cases to align with the updated client initialization and parameter handling.
    • Added tests for handling invalid token scenarios.

@coderabbitai
Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

The 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

File(s) Summary
base/src/main/java/com/tinyengine/it/common/enums/Enums.java Added a new enum value MOONSHOT_V1_8K("moonshot-v1-8k") to the FoundationModel enum.
base/src/main/java/com/tinyengine/it/config/AiChatConfig.java
base/src/main/java/com/tinyengine/it/gateway/ai/AiChatClient.java
Updated API configuration: hardcoded API URLs; modified method and constructor signatures to accept model and token; adjusted header and logging logic in AI chat requests.
base/src/main/java/com/tinyengine/it/model/dto/AiParam.java Introduced two constructors—a parameterized constructor with a foundation model map and messages list, and a no-argument constructor—to improve object creation flexibility.
base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java Enhanced error handling: added token validation, updated the foundation model handling from a string to a map, modified API client initialization, and refined response checks in the methods handling AI chat requests.
Test Files:
base/src/test/java/com/tinyengine/it/controller/AiChatControllerTest.java
base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java
base/src/test/java/com/tinyengine/it/service/app/impl/AiChatServiceImplTest.java
Updated tests: added new import statements; changed parameter types from OpenAiBodyDto to AiParam to reflect the updated method signatures; and, in one test, included a new token entry in the foundation model map and adjusted expected outcomes.

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
Loading

Suggested reviewers

  • lu-yg

Poem

I'm a bunny coding under moonlit skies,
Hopping over changes with bright, eager eyes.
New models and tokens, oh what a sight,
I nibble on updates from morning to night.
In fields of code, I joyfully prance—
A rabbit's delight in each newfound advance!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Accessing openAiBodyDto.getFoundationModel().get("model") directly could lead to NullPointerException if foundationModel is 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 a null token 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 for foundationModel or messages, 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:

  1. Moving it to a test configuration file
  2. 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:

  1. Using dependency injection
  2. Implementing a client pool
  3. 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:

  1. Add version compatibility information
  2. Include token requirements
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d2c0af and b71f885.

📒 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 for Enums and AiParam appear consistent with the new functionality.


48-49: Validate null or empty inputs for model/token.
If model or token is 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 the model doesn'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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
base/src/main/java/com/tinyengine/it/service/app/impl/AiChatServiceImpl.java (1)

79-81: ⚠️ Potential issue

Fix 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:

  1. Use a constant or meaningful test token instead of "asdf"
  2. 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:

  1. Add null checks before toString() calls
  2. Consider using Optional to handle potential nulls
  3. 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:

  1. Only handles ERNIBOT_TURBO specifically
  2. Uses hard-coded values for role and name
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between b71f885 and 4a84835.

📒 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.java

Length 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 file command in this environment. Since the test data in base/src/test/java/com/tinyengine/it/gateway/ai/AiChatClientTest.java at 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)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Moving the token to a test configuration file
  2. Using a constant with a clear name like TEST_TOKEN
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between eac27c3 and 06d60a4.

📒 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:

  1. The complete response structure
  2. The presence of required fields
  3. 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"));

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 name parameter 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);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06d60a4 and 1526e46.

📒 Files selected for processing (1)
  • base/src/main/java/com/tinyengine/it/controller/PageHistoryController.java (1 hunks)

@lu-yg lu-yg merged commit 3cdc16b into opentiny:develop Feb 21, 2025
1 check passed
Ljhhhhhh pushed a commit to Ljhhhhhh/tiny-engine-backend-java that referenced this pull request Mar 22, 2025
* 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
lu-yg pushed a commit that referenced this pull request Mar 26, 2025
* 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>
lu-yg pushed a commit to lu-yg/tiny-engine-backend-java that referenced this pull request Oct 23, 2025
* 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
lu-yg pushed a commit to lu-yg/tiny-engine-backend-java that referenced this pull request Oct 23, 2025
* 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants