Crafting a Simple Toolkit for Connecting Business Central to OpenAI

Curiosity and a keen desire to learn recently led me down a fascinating path where OpenAI’s intelligence intersects with Business Central. Inspired by a project from Dmitry Katson—a leader in the Business Central community whom I deeply admire—I embarked on my journey. Although I didn’t participate in the hackathon that sparked my interest, the idea of blending AI with ERP lingered, marking the beginning of a personal adventure in technological integration.

Acknowledging the barriers to accessing OpenAI services through Azure, I chose a more direct and accessible approach: connecting Business Central directly with OpenAI. This post chronicles my journey, not only to share a simple toolkit I developed for this integration but also to introduce a variant of Dmitry’s work, adapted to generate a Warehouse Setup series in Business Central.

It’s a tale of exploration, learning, and above all, contributing to a community that values openness and knowledge sharing. Join me on this journey through the fascinating world of AI and ERP, where the technical meets the practical, all narrated from my humble and ever-curious perspective.

Table of Contents

Scenario

Setting Up OpenAI Integration with Business Central

To kick off the integration process between Business Central and OpenAI, the first and foremost task is to obtain an API key from OpenAI. This key will serve as the gateway for your Business Central application to interact with OpenAI’s powerful AI models, enabling you to leverage GPT (Generative Pre-trained Transformer) capabilities directly within your ERP environment.

Step 1: Acquiring an OpenAI API Key

  1. Navigate to OpenAI’s API Key Management: Open your web browser and go to the OpenAI platform’s API key section at https://platform.openai.com/api-keys. Here, you’ll manage your API keys, which are essential for authenticating your requests to OpenAI’s services.
  2. Create a New API Key: If you haven’t already, you’ll need to sign up and log in to your OpenAI account. Once logged in, look for an option to create a new API key. This action will generate a unique key that you’ll use in your Business Central setup to establish a secure connection to OpenAI.

Below is an image illustrating what the API key generation page looks like:

Step 2: Configuring the OpenAI Setup in Business Central

After securing your OpenAI API key, the next step involves configuring the OpenAI Setup within Business Central to enable seamless integration. This setup is critical for defining how Business Central will communicate with OpenAI, specifying the credentials, endpoint, and model to use. Follow these instructions to configure the necessary parameters:

  1. Access the OpenAI Setup Page: In Business Central, navigate to the OpenAI Setup page. This page is where you’ll enter the details required for the integration.
  2. Configure the SecretKey: Enter the API key you obtained from OpenAI in the previous step into the SecretKey field. This key authenticates your requests to OpenAI, ensuring secure communication between Business Central and OpenAI.
  3. Set the Endpoint: In the Endpoint field, input https://api.openai.com/v1/chat/completions. This specific endpoint is used for generating text completions, enabling you to leverage the GPT models for various tasks, such as generating number series, text summaries, or any custom functionality you aim to implement. The chosen endpoint corresponds to OpenAI’s Chat API, which facilitates interactive, conversational AI models.
  4. Choose the Model: For the Model field, you’ll find a dropdown list where you can select between gpt-3.5-turbo-16k and Gpt 4 for this project. These models represent different versions of OpenAI’s GPT, gpt-3.5-turbo-16k being a highly efficient model for a wide range of tasks and Gpt 4 offering even more advanced capabilities. This field is fully customizable, allowing for future updates to include an extensive list of models as they become available.

Below is an image showing what the OpenAI Setup page looks like in Business Central:

For step 3, navigating to “Warehouse Setup” and clicking the “Generate” button opens a prompt dialog page.

This step is crucial for initiating the automatic number series generation process, essential for various warehouse operations.

At this stage, you’ll notice all series fields are blank, indicating they’re ready for generation and assignment. This ensures your warehouse setup is comprehensive and operational, facilitating efficient inventory and logistics management.

Note: This process closely mirrors the one presented by Dmitry Katson in his project, available at Dmitry’s GitHub. The core concept has been slightly adapted to focus on generating exclusive series for warehouse setups and includes an additional step to automatically initialize the warehouse setup table after obtaining the series.

The intention behind this post is not to replicate or profit from Dmitry’s work. Instead, it aims to offer an alternative approach to leveraging OpenAI directly, bypassing Azure OpenAI. This adaptation seeks to broaden access to AI-powered automation within Business Central, especially for users who might face limitations with Azure OpenAI services.

The prompt dialog provides a field for inputting the desired instructions for OpenAI to process. Based on your input and the selected AI model, the system automatically generates the most suitable number series for your requirements, streamlining workflows and ensuring data consistency and accuracy within Business Central.

After entering the prompt, a “No. Series Proposal” page will open, displaying the information provided by OpenAI. Here, users have the opportunity to accept the generated series or regenerate a new version if desired. This step ensures that the proposed number series aligns with the user’s requirements before finalizing the setup in Business Central.

Video

Code

Part I GPT OpenAI

In the provided image, we can see the structure of the Business Central project designed for integrating with OpenAI. Here’s a brief explanation of the components within the project:

  • Codeunits: This directory contains the AL files with the logic necessary for the integration. Each codeunit performs specific roles, such as managing chat completion parameters, handling messages, interacting with the OpenAI API, processing the operation’s response, and counting tokens for message length validation.
    • ChatCompletionParams.Codeunit.al: Manages parameters for OpenAI’s chat completion, like temperature and token limits.
    • ChatMessages.Codeunit.al: Handles the creation and storage of chat messages that will be sent to OpenAI.
    • OpenAI.Codeunit.al: Serves as the main connector to the OpenAI API, sending requests and receiving responses.
    • OperationResponse.Codeunit.al: Interprets the response from OpenAI, checking for success or errors.
    • TokensCountImpl.Codeunit.al: Estimates the token count of messages to ensure they stay within OpenAI’s limits.
  • Enums: This folder likely contains enumerations, which are sets of named constants; in this context, it probably defines different models of OpenAI that can be used.
    • OpenAIModel.Enum.al: Defines the available OpenAI models that can be selected for use.
  • Pages: Contains the AL files related to the user interface pages that interact with the OpenAI setup and processing.
    • OpenAISetup.Page.al: Likely a page where users can enter their OpenAI configuration settings such as API key and endpoint.
  • Tables: Stores the AL files for database tables that support the OpenAI integration.
    • OpenAISetup.Table.al: A table that likely stores the OpenAI configuration settings.

By organizing the project in this manner, developers and users can easily navigate and understand the structure of the OpenAI integration. Each part of the application is modular and serves a distinct purpose, promoting maintainability and scalability.

Codeunits

The GPT OpenAI codeunit is a cornerstone in establishing a direct link between Business Central and OpenAI, facilitating seamless communication for chat completion tasks. This codeunit is responsible for configuring the necessary authorization details for OpenAI API requests, including the endpoint, API key, and chosen AI model.

It features a GenerateChatCompletion procedure, which dynamically constructs and sends requests to OpenAI based on input from chat messages and completion parameters set within Business Central. Utilizing the REST Client codeunit, it manages the API request’s preparation, execution, and the subsequent handling of the response. This process involves serializing chat message data into JSON format, executing a POST request to the OpenAI endpoint, and interpreting the response to extract the AI-generated content.

By directly integrating with OpenAI, this codeunit bypasses the need for Azure OpenAI services, offering a streamlined, efficient path to leverage OpenAI’s capabilities within Business Central environments. This approach empowers users with the flexibility to utilize the latest AI models and features directly from OpenAI, enhancing the automation and intelligence of Business Central applications.

Part II GPT NoSeries Warehouse Setup

In the second part of the project structure, we delve into the specifics of number series generation with OpenAI in Business Central:

  • Codeunits: These AL files contain the logic specific to the generation and implementation of number series:
    • GenerateSerieswithOpenAI.Codeunit.al: Coordinates the generation of number series by interfacing with OpenAI, sending prompts, and interpreting the responses.
    • NoSeriesCopilotImpl.Codeunit.al: Implements the logic to apply the generated number series to the relevant tables and possibly handles any additional processing required post-generation.
  • Pages: This directory holds the user interface components that users interact with during the number series generation process:
    • NoSeriesProposal.Page.al: A page that likely presents the proposed number series to the user for review and approval.
    • NoSeriesProposalSub.Page.al: Could be a subpage or related page that provides additional details or actions related to the number series proposal.
    • WarehouseSetup.PageExt.al: An extension to the existing Warehouse Setup page in Business Central that probably adds functionality related to the number series proposal process.
  • PageExt: This might be a typo or shorthand for page extensions, and if it’s an extension, it likely adds or alters functionality on existing pages in Business Central to accommodate the new OpenAI integration features.
  • Tables: Contains the AL file for the database table that will store the number series proposals:
    • NoSeriesProposal.Table.al: This table is where the generated number series proposals from OpenAI are stored before being reviewed and applied to the system.

This part of the project focuses on taking the responses from OpenAI and translating them into actionable data within Business Central. It includes user interface elements that allow for user interaction and confirmation, as well as the back-end logic to apply the generated series to the system effectively.

Each component in this section is designed to ensure that the number series generation is not only automated but also integrated smoothly with the user’s workflows, providing a seamless experience from generation to application. The modularity of this approach enables easy updates and maintenance as the underlying AI technology evolves.

Codeunits

Generate Series with OpenAI

The GenerateNoSeries procedure in the “Generate Series with OpenAI” codeunit is a key component for automating number series generation in Business Central through direct integration with OpenAI. This procedure sets up authorization with OpenAI using specific endpoint, model, and secret keys, ensuring secure API communication. It dynamically constructs chat messages incorporating system prompts and user inputs, which are then sent to OpenAI for processing.

Upon receiving a response, the method evaluates the outcome: if successful, it extracts the generated number series for use within Business Central; if not, it triggers an error notification. This approach streamlines the generation of number series, showcasing the toolkit’s capability to enhance Business Central with AI-driven automation without relying on Azure OpenAI services. This method exemplifies the toolkit’s aim to facilitate direct OpenAI integration, offering businesses a flexible solution to leverage AI advancements.

GPT No. Series Copilot Impl

The ListAllWsheTablesWithNoSeries procedure within the “GPT No. Series Copilot Impl.” codeunit plays a crucial role in identifying which fields within the Warehouse Setup table could potentially require a number series. This procedure meticulously filters the fields to those that are not obsolete and are of the ‘Code’ type with a length of 20 characters, aligning with typical number series formats. It then appends the names of these fields to a system prompt, which is likely used as part of the AI’s instructions for generating appropriate number series.

Moving forward to the InsertNoSeries procedure, it’s evident that this is where the magic happens—transforming the series generated by OpenAI into tangible records within the “No. Series” table. It goes a step further by flagging these new series as manual and default, ensuring that they are readily usable within the system. If a series code already exists, it smartly opts to update rather than create a duplicate.

The innovative aspect of this procedure is its dynamic association with the “Warehouse Setup” table. By utilizing the DataTypeManagement codeunit, it locates the corresponding field within the Warehouse Setup based on the generated series description. It ensures that the Warehouse Setup is updated to reflect the newly generated series, thus keeping the system’s configuration coherent and updated.

In essence, while ListAllWsheTablesWithNoSeries sets the stage by identifying candidate fields for series application, InsertNoSeries performs the act of aligning the generated series with the system’s functional setup. Although inspired by Dmitry’s project, the inclusion of an additional step to directly update the Warehouse Setup showcases an evolution of the original concept, providing a tailored solution for Warehouse series management.

Conclusion

Embarking on the journey to integrate Business Central with OpenAI has been both enlightening and exciting. This project, inspired by Dmitry Katson’s remarkable work, has taught me invaluable lessons about the potential of AI in ERP systems. Although I long to participate in a hackathon and immerse myself in the annual tech events, this initial foray into connecting Business Central directly with OpenAI serves as a humble beginning.

The approach we’ve taken is straightforward yet distinct, offering an alternative to Azure OpenAI by linking directly with OpenAI’s API. This simplicity belies the project’s potential to revolutionize other facets of ERP beyond number series generation. I’m acutely aware that there’s ample room for enhancement, such as implementing interfaces to refine the interaction between Business Central and AI services. And who knows? With technology’s rapid pace, a direct OpenAI connection in Business Central might just be on the horizon.

I’m delighted with the knowledge gained and, as always, eager to share my contributions with the community. To those interested in delving deeper, the complete code is available on my GitHub repository. Your feedback and applications are welcome as we collectively strive to expand Business Central’s capabilities for all users.

GitHub Repository Link

3 thoughts on “Crafting a Simple Toolkit for Connecting Business Central to OpenAI

  1. Keinier Caboverde Reply

    It’s so interesting your post Ivan, I’m so proud

    • ivanrjlg Post authorReply

      Thank you so much for your kind words. I deeply appreciate the time we worked together; it was crucial for my growth and learning in this field. I look forward to sharing more successes in the future!

  2. Pingback: Crafting a Simple Toolkit for Connecting Business Central to OpenAI | Pardaan.com

Leave a Reply

Your email address will not be published. Required fields are marked *