All Products
Search
Document Center

AI Coding Assistant Lingma:Best practices for knowledge base as context for code completion

Last Updated:Jun 13, 2025

Lingma provides contextual analysis based on knowledge base for code completion. When developers use Lingma, it incorporates enterprise-uploaded code repositories as context. This ensures that code completion aligns more closely with enterprise coding standards and business characteristics. This topic describes how to build a high-quality enterprise code repository for admins, and provides best practices for backend and frontend developers.

Supported editions and languages

Edition

Backend

Frontend

Enterprise Dedicated Edition

Java, C#, C/C++, Go, Python

JavaScript, TypeScript, Vue, React

For Administrators: How to build a high-quality enterprise code repository

To make sure your code data is processed well, follow these instructions for preparing your code repositories. This helps make retrieval faster and more accurate.

Guidelines for code repository selection and preparation

This section covers two scenarios of code repository preparation:

Scenario 1: Improve efficiency in your daily development

Use multiple code repositories during enterprise development to enhance retrieval performance. This helps you find code quickly, reuse it easily, and work efficiently. Here are the guidelines:

Backend scenarios
  • [Recommended] Select high-frequency code snippets or files: Choose code snippets that appear often or are reused in the current project. These snippets are highly reusable and suitable for inclusion in a knowledge base. Organize these snippets into a separate repository and upload them to a separate knowledge base for easy management and retrieval.

  • Code of the current project: You can also upload the entire current project to a knowledge base for comprehensive retrieval. This improves code reusability and development efficiency. However, if the project contains interfering or low-quality code, this may affect the performance of code completion enhancement.

Frontend scenarios
Important

Upload a code repository that uses component libraries instead of the source code repository of components. Make sure that the repository covers as many usage scenarios as possible.

  • [Recommended] Frontend template page code repository: Assemble enterprise custom components into templates for highly reusable frontend pages, such as logon, registration, account display, and fund transfer pages. If your enterprise has a template library, we recommend uploading it to the enterprise code knowledge base.

  • Code repository of the current project: Upload well-structured and high-quality project code to the enterprise knowledge base for comprehensive retrieval. Low-quality or interfering code in the repository may affect code completion performance.

Scenario 2: Ensure code consistency and reduce repeated development in specific business scenarios

When building enterprise-level applications, make sure the business rules are the same to keep the system stable and easy to maintain. If there are no common standards, different developers might use different methods. This can lead to different business rules, make the code harder to fix, and weaken the system's stability.

Below are some use cases of specific business scenarios:

Case 1: Reuse of enterprise framework and middleware logic

An enterprise requires a unified distributed lock mechanism for its inventory management system. This can be done by integrating business frameworks into its code knowledge base. Developers can then easily use these code snippets when writing new code in their IDE. This improves development efficiency, reduces repeated development, enhances code quality, and ensures business logic consistency.

Below are some tips to select and get ready a code repository:

Figure out the required business needs and implementations:

  • Identify key business modules that require a unified implementation in your system, such as the inventory control, order processing, and payment systems.

  • Set up how to handle specific business scenarios: For example, the inventory system has different tasks like reducing stock, checking stock level, and locking stock, and each task needs a different implementation mechanism.

Choose code files for the business frameworks and upload them to a code knowledge base:

  • Filter business frameworks to find core code that handles key business logic, organize it, and upload it to a separate code knowledge base. For example, if distributed locking is required to keep them save while being updated, find the main code that implements this locking.

    /**
     * Use the enterprise-developed distributed locking mechanism to implement concurrency control
     */
    @Service
    public class InventoryService {
        
        @Autowired
        private DistributedLockFramework lockFramework;
        
        @Autowired
        private InventoryRepository inventoryRepository;
        
        /**
         * Use the distributed locking mechanism to ensure concurrency security during inventory deduction
         * @param productId, which specifies the product ID.
         * @param quantity, which specifies the deduction quantity.
         * @return, which specifies whether deduction is successful.
         */
        public boolean deductInventory(Long productId, int quantity) {
            String lockKey = "inventory:" + productId;
            return lockFramework.withLock(lockKey, 30, TimeUnit.SECONDS, () -> {
                Inventory inventory = inventoryRepository.findByProductId(productId);
                if (inventory == null || inventory.getQuantity() < quantity) {
                    return false;
                }
                inventory.setQuantity(inventory.getQuantity() - quantity);
                inventoryRepository.save(inventory);
                return true;
            });
        }
    }
Case 2: Reuse of core enterprise business logic

An enterprise wants to set up a single, personalized recommendation policy for its products. In this case, you can integrate enterprise-developed business frameworks into a code knowledge base of the enterprise. Then, developers can easily recall and reuse standardized code snippets when they write business logic in an IDE. This improves development efficiency, reduces repeated development, enhances code quality, and ensures the consistency and stability of business logic.

Below are some tips to select and get ready a code repository:

Determine the required business modules and implementations:

  • Identify key business modules: Find the parts of your business that need a unified implementation in your system, like the commodity recommendation system.

  • Define business actions and main steps. For example, a personalized recommendation policy includes these steps: collect user behavior data, figure out user interest features, get a list of possible products, score and rank these products, and show the top choices. You can use pre-written code to implement these steps.

Choose code files for the business frameworks and upload them to a code knowledge base:

  • Find the main code that handles key business logic, organize it, and upload it to a separate code knowledge base. Here is an example of a personalized recommendation policy:

    /**
     * The recommendation engine service
     * Implement personalized recommendation based on user behavior and commodity features
     */
    @Service
    public class RecommendationService {
        
        @Autowired
        private UserBehaviorRepository userBehaviorRepo;
        
        @Autowired
        private ProductRepository productRepo;
        
        /**
         * Generate a recommendation list for a specified user
         * @param userId, which specifies the user ID.
         * @param limit, which specifies the maximum number of commodities that can be recommended.
         * @return, which specifies the IDs of recommended commodities.
         */
        public List generateRecommendations(Long userId, int limit) {
            // Obtain user behavior data
            List behaviors = userBehaviorRepo.findRecentByUserId(userId, 100);
            
            // Extract user interest features
            Map userInterests = extractUserInterests(behaviors);
            
            // Obtain a candidate commodity pool
            List candidateProducts = productRepo.findRecentlyActive(1000);
            
            // Calculate and rank commodity scores
            List scoredProducts = candidateProducts.stream()
                .map(product -> new ScoredProduct(product, calculateScore(product, userInterests)))
                .sorted(Comparator.comparing(ScoredProduct::getScore).reversed())
                .collect(Collectors.toList());
            
            // Return the top-scoring commodities
            return scoredProducts.stream()
                .limit(limit)
                .map(sp -> sp.getProduct().getId())
                .collect(Collectors.toList());
        }
        
        // Other auxiliary methods
    }
Important

Add comments to the code of the main functions. This helps developers can remember code snippets when they write code in an IDE.

Case 3: Reference existing projects to improve new project efficiency

When an enterprise starts a new project, it can use the code of similar core modules in an existing project. This saves time and money, and makes the new project better and more stable.

Below are some tips to select and get ready a code repository:

Identify key business modules based on the required business and scenarios:

  • Identify similar functions or methods. For example, if both the new and old projects have functions such as user management, commodity display, and order processing, list the related modules.

  • Check code quality: Make sure that the existing project code has been fully tested and is stable and reliable. Remove extra files and configurations to keep the code clean and easy to use.

Define specific business actions and core actions:

  • Extract core functions: From the existing project, extract the code of key functional modules that can be reused. Examples:

    • User management: user registration, logon, and information modification

    • Commodity display: commodity list, details page, and search function

    • Order processing: placing order, handling payment, and updating order status

Important

Add comments to the code of the main functions. This helps developers can remember code snippets when they write code in an IDE.

Choose code files of the related business frameworks and upload them to a code knowledge base. Reorganize the code of the existing project using a modular structure. This separates the code for different teams that are responsible for specific modules in the new project. Create a separate code repository for each module:

  • Code knowledge base isolation: Upload the code of the existing project to the proper knowledge base. For example, upload the code of the user management, commodity display, and order processing modules to separate knowledge bases.

  • Permission management: Set up permissions so only right teams can access specific code. This prevents interference during code completion in IDEs.

Code file specifications

  • Supported languages and frameworks:

    • Backend: Java, Python, Go, C#, and C/C++

    • Frontend: TypeScript, JavaScript, React, and Vue

  • Upload limits: Only source code files can be uploaded. For example, upload .java files for Java, .cs files for C#, and .js or .jsx files for JavaScript.

  • Avoid uploading the following:

    • Test data and code, such as test scripts, test cases, or test-related code that does not contain business logic.

    • Mock methods, unless they contain specific business logic.

    • Build artifacts:

      • Frontend: Files generated by build tools such as Webpack and Gulp. These files are typically stored in the dist or build directory.

      • Backend: Compiled DLL files and all other compilation output.

  • Commenting guidelines:

    • Add detailed comments to function headers.

    • To distinguish functions, make sure that comments are informative. Adjust comments based on comment templates or enterprise specifications.

      /**
       * Update the status of a specified order.
       *
       * @param orderId, which specifies the unique ID of the order.
       * @param newStatus, which specifies the new status of the order.
       * @return boolean, which specifies whether the update is successful.
       */
  • Function naming convention:

    • Make sure that the function name is informative.

    • Use clear and descriptive names, such as exportOrdersToPDF and updateOrderStatus, instead of func1.

Upload guidelines

  • Compress files into .zip, .gz, or .tar.gz formats.

  • Make sure each package is no larger than 100 MB.

For Developers: How to use knowledge base as context for code completion

Backend scenarios

Comment to code

Lingma can generate code using natural language comments. Here are the best practices for backend development:

  1. Upload code to an enterprise code repository: Put the required functional code in a zipped file and upload it to the code repository. Make sure that the functions follow the comment specifications. Add comments before the functions. See Administrators: build a high-quality enterprise code repository for details. Take the comments for the Snowflake algorithm as an example:

    /**
     * Use the Snowflake algorithm to generate unique IDs
     * @param workerId
     * @return
    */
    public synchronized Long getSnowFlowerId(long workerId){
     long id = -1L;
    
     if (workerId < 0 || workerId > snowFlowerProperties.getMaxWorkerId()) {
        throw new IllegalArgumentException(
          String.valueOf("workerID must gte 0 and lte " + snowFlowerProperties.getMaxWorkerId()));
     }
    
     // Algorithm implementation code
     
    return id;
    }
  2. Enter comments: Find a Java class in your IDE and add comments that match the functions to recall. Make sure the descriptions are clear and the styles are consistent.

    Style 1

    //Please generate code that uses the Snowflake algorithm to generate a unique ID and returns the generated ID

    Style 2

    /**
     * Use the Snowflake algorithm to generate unique IDs
     * @param wId
     * @return
    */

    Comment specifications:

    • Comment length: When you code, don't use short comments. Aim for at least 15 characters. If a comment is too short, it won't trigger a recall.

    • Comment meaning: Make sure that comments are clear and accurate. Include keywords and descriptions of return values to help Lingma understand your code more accurately.

    • Multi-language support: Both English and Chinese comments are supported. The language used in repository comments can differ from that used in the code.

    • Parameter names: You can use flexible parameter names. Lingma will adjust them to match the recalled code.

    Below are some bad examples:

    • //Snowflake algorithm Issue: The comment is too short and and not detailed enough.

    • //Generate a unique ID Issue: The comment is missing keywords, which might cause confusion.

  3. Code generation: When you press Enter for the first time, Lingma suggests code based on your comments. When you press it again, Lingma completes the code using the enterprise code repository.2024-09-12_18-11-55

Generate code using function signatures

  1. Upload code to an enterprise code repository.

  2. Enter function signatures: Find a Java class in your IDE and enter the signatures of the related functions. You can use flexible parameter names. Lingma will change the parameters to match the recalled code.

    public List nextList(String name, int size)

    Function signature descriptions:

    • Function name: Use clear and meaningful function names to help match similar meanings.

    • Parameters and return values: The types and order must match the target function, but you can change parameter names. Lingma automatically adjusts the parameters to match the recalled code. Here are some examples of poor parameter names:

      • public List func1(String name, int size): The function name is unclear and does not accurately reflect the function.

      • public List nextList(int orderId): The parameter type and return value type do not match the target function.

  3. Code completion: After you press Enter for the first time, Lingma provides code completion suggestions. After you press it again, Lingma automatically completes the code based on the code in the enterprise code repository.2024-09-12_18-14-531723624742377-2a4c12e5-bdb9-438b-8732-2d0e15fd0e10.gif

Frontend scenarios

Complete frontend custom component code using tags

Lingma can generate code using tags in the frontend custom components. Here are the best practices:

  1. Upload code to an enterprise code repository: Before you start, make sure all the code for the required frontend components is uploaded to the code repository. Here is an example of the React framework:

    New
          }
          formItems={formItems}
          formRef={formRef}
          columns={columns}
          request={async (params, requestType) => {
            const res: Record = await apiGetUserList(params);
            return {
              data: res.data,
              total: res.total,
            };
          }}
    />
  2. Write component code: Open the .jsx file in your IDE and start coding. Use basic HTML tags or custom component tags, such as <LTable />.

  3. Enable code completion: Once you've typed enough code to trigger a match in the library, the IDE will generate complete component code for you. You can also press Enter to manually complete the code.2024-09-12_18-17-56

    Important

    Trigger code completion within a complete component label.

Comment to code

Lingma can generate code using natural language comments. Here are the best practices:

  1. Upload code to an enterprise code repository: Put the required functional code in a zipped file and upload it to the code repository. Make sure that the functions follow the comment specifications and have comments at the top. See Administrators: build a high-quality enterprise code repository for details. Example:

    /**
     * Generate an object with id as the key value based on the error message
     * @param {Array} results
     * @return {Record}
    */
    function getErrObj(results) {
      // Function implementation code
    }
  2. Enter comments: Open the required JavaScript file in your IDE and add comments. Here is an example:

    //Generate an object with id as the key value based on the error message

    Comment specifications:

    • Comment length: When you code, don't use short comments. Aim for at least 15 characters. If a comment is too short, it won't trigger a recall.

    • Comment meaning: Make sure that comments are clear and accurate. Include keywords and descriptions of return values to help Lingma understand your code more accurately.

    • Multi-language support: Both English and Chinese comments are supported. The language used in repository comments can differ from that used in the code.

    • Parameter names: You can use flexible parameter names. Lingma will adjust them to match the recalled code.

  3. Code generation: When you press Enter for the first time, Lingma suggests code based on your comments. When you press Enter again, Lingma completes the code using the enterprise code repository.2024-09-12_18-16-56

Note
  • If your comments or function signatures have parameters, Lingma automatically changes the parameter names in the generated code to ensure naming consistency.

  • To get the latest data, refresh the cache. Press ⌥(option) P on macOS or Alt P on Windows to manually trigger code completion.

FAQ: Why can't I recall code?

If you have trouble recalling code after installing Lingma, perform the following steps:

  • macOS: Restart the Lingma process and clear the related cache:

    ps -ef|grep lingma|grep start|awk '{print $2}'|xargs -I {} kill -9 {}
  • Windows: Terminate the Lingma process in Task Manager.