Path: blob/master/cpd5.2/notebooks/python_sdk/experiments/autoai_rag/Use AutoAI RAG with watsonx Text Extraction service.ipynb
6412 views
Use AutoAI RAG with watsonx Text Extraction service
Disclaimers
Use only Projects and Spaces that are available in the watsonx context.
Notebook content
This notebook demonstrates how to process data using the IBM watsonx.ai Text Extraction service and use the result in an AutoAI RAG experiment. The data used in this notebook is from the Granite Code Models paper.
Some familiarity with Python is helpful. This notebook uses Python 3.11.
Learning goal
The learning goals of this notebook are:
Process data using the IBM watsonx.ai Text Extraction service
Create an AutoAI RAG job that will find the best RAG pattern based on processed data
Contents
This notebook contains the following parts:
Install and import the required modules and dependencies
Connect to WML
Authenticate the Watson Machine Learning service on IBM Cloud Pak for Data. You need to provide the platform url
, your username
, and your api_key
.
url
- url which points to your CPD instance.username
- username to your CPD instance.api_key
- api_key to your CPD instance.
Alternatively, you can use your username and password to authenticate WML services.
Create an instance of APIClient with authentication details
Working with spaces
First, you need to create a space for your work. If you do not have a space already created, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data
to create one.
Click New Deployment Space
Create an empty space
Go to the space
Settings
tabCopy the
space_id
and paste it below
PLATFORM_URL
is the url which points to your CPD instance.
Tip: You can also use SDK to prepare the space for your work. Find more information in the Space Management sample notebook.
Action: Assign the space ID below
To be able to interact with all resources available in Watson Machine Learning, set the space that you are using.
Create an instance of COS client
Connect to the Cloud Object Storage instance for the by using the ibm_boto3
package (for detailed explanation how to do this see IBM Cloud Object Storage connection).
Action: Assign COS credentials below
Initialize the connection to the created and get the connection ID.
Prepare data and connections for the Text Extraction service
The document, from which we are going to extract text, is located in the IBM Cloud Object Storage (COS). In this notebook, we will use the Granite Code Models paper as a source text document. The final results file, which will contain extracted text and necessary metadata, will be placed in the COS. So we will use the ibm_watsonx_ai.helpers.DataConnection
and the ibm_watsonx_ai.helpers.S3Location
class to create Python objects that will represent the references to the processed files. Reference to the final results will be used as an input for the AutoAI RAG experiment.
Create an input connection.
Download the document from the url and upload to the COS Bucket using created connection.
Output file connection.
Run a text extraction job for connections created in the previous step.
Wait for the job to be complete.
Get the text extraction result.
Granite Code Models: A Family of Open Foundation Models for Code Intelligence
Mayank Mishra⋆ Matt Stallone⋆ Gaoyuan Zhang⋆ Yikang Shen Aditya Prasad Adriana Meza Soria Michele Merler Parameswaran Selvam Saptha Surendran Shivdeep Singh Manish Sethi Xuan-Hong Dang Pengyuan Li Kun-Lung Wu Syed Zawad Andrew Coleman Matthew White Mark Lewis Raju Pavuluri Yan Koyfman Boris Lublinsky Maximilien de Bayser Ibrahim Abdelaziz Kinjal Basu Mayank Agarwal Yi Zhou Chris Johnson Aanchal Goyal Hima Patel Yousaf Shah Petros Zerfos Heiko Ludwig Asim Munawar Maxwell Crouse Pavan Kapanipathi Shweta Salaria Bob Calio Sophia Wen Seetharami Seelam Brian Belgodere Carlos Fonseca Amith Singhee Nirmit Desai David D. Cox Ruchir Puri† Rameswar Panda†
IBM Research
⋆Equal
Contribution
†Corresponding Authors [email protected], [email protected]
Abstract
Large Language Models (LLMs) trained on code are revolutionizing the software development process. Increasingly, code LLMs are being inte grated into software development environments to improve the produc tivity of human programmers, and LLM-based agents are beginning to show promise for handling complex tasks autonomously. Realizing the full potential of code LLMs requires a wide range of capabilities, including code generation, fixing bugs, explaining and documenting code, maintaining repositories, and more. In this work, we introduce the Granite series of decoder-only code models for code generative tasks, trained with code written in 116 programming languages. The Granite Code models family consists of models ranging in size from 3 to 34 billion parameters, suitable for applications ranging from complex application modernization tasks to on-device memory-constrained use cases. Evaluation on a comprehensive set of tasks demonstrates that Granite Code models consistently reaches state-of-the-art performance among available open-source code LLMs. The Granite Code model family was optimized for enterprise software devel opment workflows and performs well across a range of coding tasks (e.g. code generation, fixing and explanation), making it a versatile “all around” code model. We release all our Granite Code models under an Apache 2.0 license for both research and commercial use.
https://github.com/ibm-granite/granite-code-models
1 Introduction
Over the last several decades, software has been woven into the fabric of every aspect of our society. As demand for software development surges, it is more critical than ever to increase software development productivity, and LLMs provide promising path for augmenting human programmers. Prominent enterprise use cases for LLMs in software development productivity include code generation, code explanation, code fixing, unit test and documentation generation, application modernization, vulnerability detection, code translation, and more.
Recent years have seen rapid progress in LLM’s ability to generate and manipulate code, and a range of models with impressive coding a
Define a connection to COS Bucket and upload a json
file to use for benchmarking.
Note: correct_answer_document_ids
must refer to the document processed by text extraction service, not the initial document.
Benchmarking data.
Create a connection.
Upload benchmarking data to COS Bucket.
Define the connections to the test data and input data for the AutoAI RAG experiment, using the output of the Text Extraction job as the input connection.
Call the run()
method to trigger the AutoAI RAG experiment. Choose one of two modes:
To use the interactive mode (synchronous job), specify
background_mode=False
To use the background mode (asynchronous job), specify
background_mode=True
Get the selected pattern
Get the RAGPattern object from the RAG Optimizer experiment. By default, the RAGPattern of the best pattern is returned.
Test the RAGPattern by querying it locally.
Deploy the RAGPattern
To deploy the RAGPattern, store the defined RAG function and then create a deployed asset.
Test the deployed function
The RAG service is now deployed in our space. To test the solution, run the cell below. Questions have to be provided in the payload. Their format is provided below.
Question: What training objectives are used for the models?
Answer: The models are trained using the causal language modeling objective and the Fill-In the-Middle (FIM) objective. The FIM objective is designed to predict inserted tokens given a context and subsequent text. The models are trained to work with both PSM (Prefix-Suffix-Middle) and SPM (Suffix-Prefix-Middle) modes, using relevant formatting control tokens. The overall loss is computed as a weighted combination of the two objectives, with α empirically set to 0.5 during training. The FIM objective is only used during pretraining, and is dropped during instruction finetuning.
Reference(s): Document 4.2 Training Objective For training of all our models, we use the causal language modeling objective and Fill-In the-Middle (FIM) (Bavarian et al., 2022) objective. The FIM objective is tasked to predict inserted tokens with the given context and subsequent text. We train our models to work with both PSM (Prefix-Suffix-Middle) and SPM (Suffix-Prefix-Middle) modes, with relevant formatting control tokens, same as StarCoder (Li et al., 2023a). The overall loss is computed as a weighted combination of the 2 objectives: L = αLCLM + (1 − α)LF IM (1) We emperically set α = 0.5 during training and find that this works well in practice leading to SOTA performance on both code completion and code infilling tasks. It should be noted that the FIM objective is only used during pretraining, however we drop it during instruction finetuning i.e we set α = 1.
Is there anything else you would like to know?
Summary
You successfully completed this notebook!
You learned how to use AutoAI RAG with documents processed by the TextExtraction service.
Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.
Author:
Witold Nowogórski, Software Engineer at watsonx.ai.
Copyright © 2025 IBM. This notebook and its source code are released under the terms of the MIT License.