IBM Cloud Pak for Data

IBM Cloud Pak for Data

Come for answers. Stay for best practices. All we’re missing is you.

 View Only

Building a Trustworthy Chemical Extraction Pipeline: Synthetic Data, Chemical Name to Formula, and Governed Prompt Tuning on IBM watsonx.ai

By PRAVEENA HARIKUMAR posted 09/30/26 07:28 AM

  

Written by @Greeshma Babu and @PRAVEENA HARIKUMAR

Reviewed by @SWATI NANDA

Introduction:

In chemical research, pharmaceuticals, and materials science, vast amounts of critical composition data are locked within unstructured text — lab notes, safety data sheets (SDS), patent filings, and quality assurance logs. Translating descriptive chemical mixture narratives into standardized chemical formulas (e.g., “The suspension contains Magnesium Hydroxide at 400 mg per 5 mL, Aluminum Hydroxide at 400 mg per 5 mL, and Simethicone at 40 mg per 5 mL.”) is crucial for downstream analytics, predictive modeling, and compliance reporting.

IBM Software Hub provides an integrated enterprise platform to automate chemical compounds extraction, structure the unstructured mixture records, and govern the resulting AI workflows. 

In this tutorial, we will walk you through an end-to-end workflow on IBM Software Hub: ingesting chemical mixture texts, extracting referenced chemical compounds and elements in order of appearance, mapping them to their exact chemical formulas, and tracking the prompt engineering lifecycle from development to production.

Use Case Overview: 

A chemical research enterprise receives thousands of unstructured mixture formulation descriptions daily. Manual extraction of individual reagents, acids, bases, and salts is slow, prone to transcription errors, and creates bottlenecks in batch verification pipelines.

The enterprise needs an automated AI solution to:

  • Extract all chemical elements, acids, and compounds mentioned in narrative text sentences.
  • Map common chemical nomenclature to standardized chemical formulas (e.g., Sulfuric Acid → H₂SO₄, Sodium Hydroxide → NaOH).
  • Output an ordered, comma-separated target formula string for direct ingestion into laboratory information management systems (LIMS).
  • Use the extracted chemical information for downstream safety and compliance validation, including identifying hazardous substances, triggering rejection rules, and flagging chemicals that are not permitted.
  • Track model precision, faithfulness, and governance lifecycle across Develop, Validate, and Operate phases using IBM watsonx.governance.

image

Fig 1: Architectural diagram

Services Required:

  • IBM Watson OpenScale: Used for model monitoring, payload evaluation, and Drift v2 tracking in production.
  • IBM watsonx.ai: Enables prompt engineering, foundation model access (Prompt Lab), and extraction template authoring.
  • IBM watsonx.governance: Handles model factsheet generation, lifecycle management, and regulatory compliance.
  • Synthetic Data Generator: Expands the training dataset by generating realistic, diverse chemical mixture descriptions that mimic the original source data.
  • Jupyter Notebook: Parses mixture descriptions and engineers a structured formula column (e.g. H₂SO₄, NaOH) used as ground-truth input for Prompt Lab training.

Persona Setup:

We recommend using the following out-of-the-box roles for this tutorial.

The cpadmin user (administrator) is used to create and configure other users in the system. Each user is then assigned specific roles that define their capabilities and permissions within IBM Software Hub.

IBM Documentation link for predefined roles on IBM Cloud: https://dataplatform.cloud.ibm.com/docs/content/wsj/catalog/roles-wkcop.html?context=cpdaas&audience=wdp&locale=en

  • Data Engineer: Manages data ingestion and generates synthetic data
  • Data Scientist: Builds, trains, deploys, and evaluates models.
  • Data Steward: Create and Manage AI Use case
  • Data Quality Analyst: Lab Safety & Compliance Auditor (Report administrator, Create dashboard)

Pre-Configuration :

Before proceeding with workspace association and AI use case development, ensure the following services are installed and provisioned on your cluster:

  • Db2 OLTP
  • Watson OpenScale
  • Watson OpenPages

Ensure all persona users have access to the above services.

Configuring users in IBM Watsonx Governance :

1. Log in with the cpadmin user, go to Service instances, open OpenPages, and launch the IBM Watsonx governance console; click the gear icon, go to Users and Security, select Users and choose the modown user.

2. Under Locale and Profiles, click the pencil icon, search for “watsonx”, check all four watsonx- governance profiles, and save.

3. In Role Assignments, click Assign Roles, set Role Type to Business Permissions role template. Entity, and select the “MRG — All"

4. Under Security Domains, check all options including Library and RCSA Staging Hierarchy, then click Assign.

5. Click the profile icon in the top right, select Change Profile, choose watsonx-governance Modules Master, and click Save.

Note: Repeat these steps for all relevant users involved in the AI use case lifecycle.

Step 1: Create a Centralized inventory and AI Use Case

1. Log in as cpadmin user and  go to Inventories, click New Inventory, name it Central Inventory, enable “Add collaborators after creation”, then click Create and add required collaborators (Data Scientist, Data Steward, Data Engineer and Data Quality Analyst).

2. Log in as Data Steward User (dstw), open Enterprise Model Inventory, click New AI Use Case.

3. Enter the following:

  • Name: Automated Chemical Entity Extraction and Formula Standardization 
  • Owner: Data Steward User
  • Description: Automated extraction of chemical entities from mixture descriptions and mapping to standardized chemical formulas

4. Select the Primary Business Entity from the Catalogs section and click Save.

5. After creation, use the Third Party Link to open the use case in the IBM Watsonx Governance Console (OpenPages) .

6. Log out from cpadmin.

7. Log in with Data Quality Analyst User, go to Automated Chemical Entity Extraction and Formula Use case and enter the risk level (High based on manufacturing compliance impact).

Fig 2: AI Use case in governance console

Step 2: Set Up and Associate Workspaces Across AI Lifecycle Phases

For this use case, we will progress through three key phases: Model Development, Model Validation (pre-production), and finally Operate (production phase).

Develop Phase

1. Log in as the Data Scientist user and create a project named “ChemExtractAI Develop”.

2. Add the required collaborators (Data Scientist, Data Steward, Data Engineer and Data Quality Analyst Group).

3. From the navigation menu, go to AI Use cases and open the “Automated Chemical Entity Extraction and Formula Standardization” Use case.

4. In the Associated Workspaces section, click Associate Workspace for the Develop phase and select the project ChemExtractAI Develop.

Validate Phase

1. Log in as the Data Scientist user and create the project “ChemExtractAI Validate” then add appropriate collaborators.

2. Open the “Automated Chemical Entity Extraction and Formula Standardization” Use case from the AI Use cases menu and associate the Validation phase with the “ChemExtractAI Validate” project.

Operate Phase

1. Log in as the Data Scientist user and create a deployment space named “ChemExtractAI Deployment Space” from the Deployments section in the navigation menu. Add the appropriate collaborators (Data Steward, Data Scientist and Data Quality Analyst Group).

2. Open the Automated Chemical Entity Extraction and Formula Standardization” Use case from the AI Use cases menu and associate the Operate phase with the “ChemExtractAI Deployment Space”.

3. Log out from Data Scientist user.

Fig 3: Associating workspace in AI use case

Step 3 : Get the asset in the Project

There are different ways to add an asset to the project, such as through Data Virtualization, a direct connection, or by importing a local file.

  1. Log in as Data Engineer user → Go to Project, Click on Import assets → local file → Browse the asset from the system.

Step 4 : Generate the synthetic data

  1. Log in as Data Engineer user
  2. Navigate to your project workspace “ChemExtractAI Develop” and click New asset, then select Generate synthetic tabular data to create a synthetic data flow.
Fig 4: Creating Synthetic data generator


3. In the Welcome to Synthetic Data Generator dialog, select First time user to open the Generate synthetic tabular data flow window, which helps you set up your first flow

Fig 5: Synthetic data  generator wizard

4. Select Leverage your existing data → Click on Continue

5. Click on Select data from project → Click on Data Asset → Select the asset → Click on Select button

Fig 6: Select seed file for synthetic data generator

6. Click on Next Button

7. In the Anonymize tab, select the columns with data that you want to mask. This can disguise column names, column values, or both.

8. In the Mimic tab, configure parameters for how Synthetic Data Generator generates the synthetic data.

Fig 7: Select mimic options screen

9. Skip Evaluate settings → Click on Next.

10. Enter File name for Export data → Select the File type → Click on Next.

Fig 8: Export option screen

Fig 9: Review screen

11. Click on Save Flow.

12. Save the Flow → Click on Run Flow.

Fig 10: Run flow screen

13. Wait for the flow to complete.

14. New asset is generated with specified the name and type in the project.

Fig 11:Data generated after successful run

15. Profile the generated asset and log out from data engineer user.

Fig 12: Profiled asset

Step 5: Use Notebook to extract Chemical Mixture and Formula Mapping 

  1. Log in as the Data Scientist
  2. Open Project “ChemExtractAI Develop” and click New asset, then select Jupyter Notebook to create a Notebook.
    import re
    import itc_utils.flight_service as itcfs
    import pandas as pd
    from ibm_watson_studio_lib import access_project_or_space
    
    # ==============================================================================
    # 1. DEFINE CHEMICAL MAPPING & EXTRACTION LOGIC
    # ==============================================================================
    CHEMICAL_MAPPING = {
        "aluminum": "Al",
        "copper": "Cu",
        "iron": "Fe",
        "zinc": "Zn",
        "magnesium": "Mg",
        "calcium": "Ca",
        "sodium": "Na",
        "potassium": "K",
        "nickel": "Ni",
        "chromium": "Cr",
        "manganese": "Mn",
        "titanium": "Ti",
        "cobalt": "Co",
        "silver": "Ag",
        "gold": "Au",
        "lead": "Pb",
        "tin": "Sn",
        "mercury": "Hg",
        "hydrochloric acid": "HCl",
        "sulfuric acid": "H₂SO₄",
        "nitric acid": "HNO₃",
        "phosphoric acid": "H₃PO₄",
        "acetic acid": "CH₃COOH",
        "hydrofluoric acid": "HF",
        "sodium hydroxide": "NaOH",
        "potassium hydroxide": "KOH",
        "calcium hydroxide": "Ca(OH)₂",
        "sodium chloride": "NaCl",
        "potassium chloride": "KCl",
        "calcium carbonate": "CaCO₃",
        "sodium carbonate": "Na₂CO₃",
        "sodium bicarbonate": "NaHCO₃",
        "calcium chloride": "CaCl₂",
        "magnesium sulfate": "MgSO₄",
        "copper sulfate": "CuSO₄",
        "zinc oxide": "ZnO",
        "iron oxide": "Fe₂O₃",
        "aluminum oxide": "Al₂O₃",
        "silicon dioxide": "SiO₂",
        "sodium nitrate": "NaNO₃",
        "potassium nitrate": "KNO₃",
        "potassium sulfate": "K₂SO₄",
        "ammonia": "NH₃",
        "hydrogen peroxide": "H₂O₂",
        "ethanol": "C₂H₅OH",
        "methanol": "CH₃OH",
        "acetone": "C₃H₆O",
        "benzene": "C₆H₆",
        "toluene": "C₇H₈",
        "phenol": "C₆H₅OH",
    }
    
    
    def extract_chemical_formulas(text, mapping_dict=CHEMICAL_MAPPING):
        if not isinstance(text, str) or not text.strip():
            return ""
        sorted_chemicals = sorted(mapping_dict.keys(), key=len, reverse=True)
        found_matches = []
        for chem_name in sorted_chemicals:
            pattern = r"\b" + re.escape(chem_name) + r"\b"
            for match in re.finditer(pattern, text, flags=re.IGNORECASE):
                start, end = match.span()
                formula = mapping_dict[chem_name]
                overlap = any(
                    not (end <= existing_start or start >= existing_end)
                    for existing_start, existing_end, _ in found_matches
                )
                if not overlap:
                    found_matches.append((start, end, formula))
        found_matches.sort(key=lambda x: x[0])
        return ", ".join(formula for _, _, formula in found_matches)
    
    
    # ==============================================================================
    # 2. READ INPUT DATA VIA FLIGHT SERVICE
    # ==============================================================================
    nb_data_request = {
        "data_name": "chemical_mixture.csv",  # or 'connected_data_name': 'chemical_mixture.csv'
        "interaction_properties": {},
    }
    flight_descriptor = itcfs.get_flight_descriptor(nb_data_request=nb_data_request)
    flightClient = itcfs.get_flight_client()
    flightInfo = flightClient.get_flight_info(flight_descriptor)
    df_0 = itcfs.read_pandas_and_concat(flightClient, flightInfo, timeout=240)
    print(f"Data read successfully. Shape: {df_0.shape}")
    
    # ==============================================================================
    # 3. APPLY CHEMICAL EXTRACTION
    # ==============================================================================
    text_col = df_0.columns[0]
    df_0["target_chemical_formula"] = df_0[text_col].apply(
        extract_chemical_formulas
    )
    
    # ==============================================================================
    # 4. FIX: DELETE CORRUPTED ASSET AND SAVE FRESH DATA ASSET
    # ==============================================================================
    wslib = access_project_or_space()
    csv_bytes = df_0.to_csv(index=False).encode("utf-8")
    
    # Step 4a: Force delete the specific broken asset ID from the error
    broken_asset_id = "01a0edb4-6179-724a-867b-743695f1759d"
    try:
        wslib.assets.delete_asset(broken_asset_id)
        print(f"Successfully deleted broken asset ID: {broken_asset_id}")
    except Exception as e:
        pass
    
    # Step 4b: Save using clean asset name (with auto-fallback to guaranteed fresh name)
    try:
        target_name = "chemical_mixtures_processed.csv"
        wslib.save_data(target_name, csv_bytes, overwrite=True)
        saved_name = target_name
    except Exception as e:
        # If the project catalog still locks that specific name, save to output name
        saved_name = "chemical_mixtures_output.csv"
        wslib.save_data(saved_name, csv_bytes, overwrite=True)
    
    print(
        f"\nSUCCESS! File '{saved_name}' is now available in your CP4D Project Assets tab."
    )
    display(df_0.head(10))
 Fig 13: Jupyter Notebook created

3. This notebook parses unstructured chemical mixture text sentences from a CSV/DataFrame, extracts each referenced chemical compound/element, maps them to their standardized chemical formulas, and creates a new target column containing comma-separated formulas.

Example:

  • Input Text: "The chemical mixture contains Aluminum at 15%, Hydrochloric Acid at 20%, and Calcium Carbonate at 8%."
  • Output Target Column: "Al, HCl, CaCO3" (or "Al, HCl, CaCO₃")

Fig 14: Notebook Successfully Ran

4. Validate the generated output file.

Fig 15: Generated asset from notebook

5. Profile the output csv file generated.

 
Fig 16: Profiled asset

            

Step 6: Prompt Template Evaluation — Develop Phase

1. Log in as Data Scientist , open the “ChemExtractAI Develop” and upload the Chemical Mixture Test Dataset — Development project.

2. In the project, click New Asset and select “Chat and build prompts with foundation models” (Prompt Template).

3. In the Structured tab, choose the foundation model: granite-13b-instruct v2.

4. Open Model Parameters and set the following:

  • Max Tokens: 20
  • Decoding Method: Greedy
  • Repetition Penalty: 1

5. Enter the prompt instruction and define the prompt variable {mixture_text} using the {#} icon.

Prompt Instruction:

You are a research chemist. Given an unstructured text description of a chemical mixture containing elements, acids, bases, or salts, extract each chemical component in the order it appears and map it to its exact standard chemical formula. Output ONLY a comma-separated list of chemical formulas. Do not include percentages, fillers, or conversational text.

Input Mixture: {mixture_text}
Chemical Formulas:

6. Go to the Try section of the prompt template, test with a complex sample (e.g., “Each capsule contains Ascorbic Acid at 500 mg, Calcium Carbonate at 250 mg, Ferrous Fumarate at 30 mg, and Zinc Sulfate at 20 mg.”), and verify the output generates C6H8O6, CaCO3, ZnSO4, FeC₁₂H₁₄O₄.

Fig 17: Prompt lab for extraction

7. Click Save As in the prompt template editor, name it Chemical Extraction Template, set the task type to Extraction, and click Save.

8. Evaluation of prompt template:

  •  Go to Project Assets tab, open the overflow menu on the prompt template, and click Evaluate.
  •  Associate a Watson Machine Learning instance and run evaluation using test data with ground-truth formulas generated from notebook.
Fig 18: Notebook output data as training data

  •  The alerts observed in the Generative AI Quality metric (Faithfulness, Exact Match, ROUGE-1/BLEU) are minimized due to zero-shot calibration.

Fig 19: Prompt lab evaluation

Step 7: Tracking the AI Use Case in Lifecycle — Develop Phase

1. Log in to IBM Software Hub as the Data Scientist.

2. After evaluating the prompt template, click on the overflow menu on the template and select AI Factsheet.

3. In the AI Factsheet, click Track in AI Use case.

4. Select the Custom Approach, then choose New Asset Record and select the version (1.0.0).

Fig 20: Versioning

5. Review all details and confirm to track the prompt template.

6. Once tracking is enabled, the Develop phase will appear highlighted in the AI Use Case Lifecycle.

Fig 21: Track in AI Use case

7. Go to the use case and from the actions menu, select “Submit the use case for initial approval”.

Step 8: Import Develop Project into Validate Project

  1. Log in as the Data Scientist and open the “ChemExtractAI Validate”. Click the project dropdown menu (top-right) and select Export Project.
Fig 22 : Export project

2 . Enter a name, select the assets to include and export the ZIP file.

3 . Log in as data scientist and open the Validation Project.

4 . Click the project dropdown and choose Import Project.

5 . Upload the exported ZIP file from the Develop phase.

Fig 23: Import project

Step 9: Validation Data Preparation

  1. Run the imported synthetic data generator  to create a new test dataset.
  2. Run the notebook to update the target column containing comma-separated formulas.

Step 10 : Evaluation and Tracking of Prompt Template — Validate Phase

1. Log in to IBM Software Hub as the data scientist.

2. Open the Validation Project and locate the imported prompt template.

3. Evaluate the prompt template using holdout validation data containing diverse multi-component mixtures (e.g., Titanium + Phosphoric Acid + Potassium Sulfate → Ti, H₃PO₄, K₂SO₄).

4. Verify that precision and faithfulness exceed 98% with zero hallucinated chemical formulas.

5. Track the prompt template in the AI Factsheet of the Validation project, registering version 1.0.1.

Fig 24: Evaluate in validate phase

Step 11: Submit AI Use Case for Approval and Complete Questionnaire in IBM Watson Governance

1. Log in back to cluster as Data Quality Analyst User.

2. Click on AI use case Automated Chemical Entity Extraction and Formula Standardization use case from main navigation menu, go to the Use Case section → from the Actions menu, select Submit for initial approval.

3. Click the Home button (top left), then go to the My Tasks tab.

4. Confirm that two questionnaires are generated for the use case (AI Risk Identification and Applicability Assessment).

Fig 25: Questionnaire 1

Fig 26: Questionnaire 2

5. Open each questionnaire, review, and complete them.

6. Go to the Admin tab of the use case.

7. Change the status of the use case to “Approved for deployment”.

Step 12: Promote Prompt Template to Deployment Space

1. Log in as Data Scientist, open the Validation Project.

2. In Assets, locate the Prompt Template.

3. Click the overflow menu (⋮) → select Promote to deployment space.

4. Choose the deployment space (ChemExtractAI Deployment Space) and confirm.

5. From the prompt template’s overflow menu in the space, click Deploy.

6. Select Online Deployment, name it Chemical Formula Extraction Deployment, and deploy.

Fig 27: Promote to space

Step 13 : Evaluate Prompt Template in Operate Phase

  1. Log in to IBM Software Hub as the Data Scientist and open the ChemExtractAI Deployment Space.
  2. Upload your test data.
  3. Locate and open the deployed prompt template, then go to the Test tab.
Fig 28: Create deployment

4. Enter sample mixture descriptions, click Generate, and review the output formulas for formatting and precision.

5. Switch to the Evaluate tab, click Activate now, then select Evaluate now.

6. Upload Payload data (streaming mixture inputs) and Feedback data (verified chemical targets).

Fig 29: Setting up for evaluation

7. Run evaluation to generate operational metrics for Generative AI Quality.

Fig 30: Evaluation

8. Navigate to the AI Use Case Lifecycle tab, click on “Export Report”, and download the AI Factsheet report as a PDF.

                                                                                               
Fig 31: Download the AI factsheet pdf document


 9. Open the AI Factsheet to review the full lifecycle summary.

Fig 32: Download AI FactSheet

Conclusion :

The real value of governed chemical AI goes beyond converting unstructured text into standardized formulas — by combining the semantic capabilities of IBM watsonx.ai with the governance and traceability of IBM watsonx.governance, organizations can transform raw chemical information into actionable intelligence. This creates a continuous intelligence layer across laboratories, suppliers, manufacturing, and regulatory processes, where every AI-generated decision remains explainable and auditable. As formulation data continues to grow, this approach evolves into an intelligent safety and compliance ecosystem identifying emerging risks earlier, incorporating regulatory changes faster, and supporting critical decisions with evidence, moving organizations from reactive chemical analysis to proactive chemical intelligence, and turning complex scientific data into safer products, faster research, and more responsible innovation.

Get started today, and let us know how your pipeline evolves we’d love to hear from you.

 #watsonxai #watsonxgovernance #IBMSoftwareHub #CloudPakforData #PromptEngineering #PromptTuning #GenerativeAI #FoundationModels #SyntheticData #AIGovernance #ModelGovernance #AILifecycle #AIFactsheet #DataScience #NLP #Spotlight #Tutorial #IBMCommunity

0 comments
42 views

Permalink