Experiencing code generation/documentation with “watsonx code assistant”.

Image description

Introduction

IBM® watsonx™ Code Assistant is poised to revolutionize the way developers write code. Imagine having an intelligent partner that understands the nuances of popular programming languages like Go, C++, Java, Python, and JavaScript, offering insightful suggestions and streamlining your workflow directly within your familiar IDE. This innovative, generative AI coding companion promises to accelerate your productivity and simplify complex coding tasks, all while prioritizing trust, security, and compliance. Let’s delve into how watsonx Code Assistant can become your indispensable ally in the world of software development.

How to install locally in your IDE (VS Code/VSCodium…)

Nothing more easy, just use the extension marketplace and install it 😁 (link provided at the end of this post).

Image description

Image description

Flavors of WCA

watsonx Code assistant comes with different flavors.

  • watsonx Code Assistant for Z (🖥️ mainframe): watsonx™ Code Assistant for Z accelerates the mainframe application development and modernization with Generative AI and automation. It supports developers in every phase of lifecycle — from application discovery and analysis to automated refactoring, code explanation, generation, optimization, and transforming to newer languages and testing. The outcome? Lower modernization risks, enhanced developer productivity and skill set and faster time to value.

Image description

  • watsonx Code Assistant for Ansible: IBM watsonx™ Code Assistant for Red Hat® Ansible® Lightspeed is designed to streamline and automate the Ansible development cycle, driving IT efficiency and scalability with trusted AI. It simplifies content creation with natural language Playbook generation, detailed explanations, and a customizable model that provides tailored recommendations, helping to ensure a confident and enhanced experience for developers at any skill level.

Image description

  • General purpose: leverages Granite models to augment developer skill sets, simplifying and automating your development and modernization efforts. It also provides IP indemnification and transparency through real-time similarity checks, ensuring code integrity and compliance with built-in assessments and chat features.

Image description

Tests

Image description

Disclaimer: Even with the remarkable capabilities of AI code assistants like watsonx, the wisdom of experienced developers rings true: generated code, no matter how promising, should never be deployed directly into a production environment without thorough scrutiny. Consider the AI as a highly skilled, yet still developing, collaborator. While it can significantly accelerate development, rigorous testing, validation, and human oversight remain crucial steps to ensure the reliability, security, and overall quality of the final product. Treat the AI’s output as a valuable starting point, not the definitive end result.

OK, now let’s jump into some tests.

First case: building a generic “Operator Framework” to wrap an application for deployment on a Kubernetes cluster.

  • Query: write a kubernetes operator framework template in Go!
  • Output ⬇️
Creating a full Kubernetes Operator framework in Go is beyond the scope of this platform due to its complexity and length. However, I can provide you with a basic template to get you started. This template will include the necessary boilerplate code for a simple Kubernetes Operator written in Go.

First, make sure you have the Kubernetes Go client installed:
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
go get k8s.io/client-go@kubernetes-1.21.0
Now, create a new directory for your Operator and initialize a Go module:
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
my-operator/
│
├── main.go
├── api/
│   └── v1/
│       └── mycustomresource_types.go
├── controllers/
│   └── mycustomresource_controller.go
├── config/
│   └── kubeconfig
└── pkg/
    └── controller/
        └── controller.go
Here's the content for each file: main.go
// main.go
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
package main

import (
 "k8s.io/apimachinery/pkg/runtime"
 ctrl "sigs.k8s.io/controller-runtime"

 myoperatorv1 "github.com/yourusername/my-operator/api/v1"
)

var (
 scheme   = runtime.NewScheme()
 setupLog = ctrl.Log.WithName("setup")
)

func main() {
 setupLog.Info("setting up controller")

 // Add MyCustomResource kind to the scheme
 myoperatorv1.AddToScheme(scheme)

 // Create a new Ctrl manager
 mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  Scheme:             scheme,
  MetricsBindAddress: ":8080",
 })
 if err != nil {
  setupLog.Error(err, "unable to start manager")
  os.Exit(1)
 }

 // Register controllers
 if err := (&myoperatorv1.MyCustomResource{}).SetupController(mgr); err != nil {
  setupLog.Error(err, "unable to create controller", "controller", "MyCustomResource")
  os.Exit(1)
 }

 // Start the manager
 setupLog.Info("starting manager")
 if err := mgr.Start(); err != nil {
  setupLog.Error(err, "problem running manager")
  os.Exit(1)
 }
}
// api/v1/mycustomresource_types.go
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
package v1

import (
 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// MyCustomResourceSpec defines the desired state of MyCustomResource
type MyCustomResourceSpec struct {
 // Add fields here
}

// MyCustomResourceStatus defines the observed state of MyCustomResource
type MyCustomResourceStatus struct {
 // Add fields here
}

// MyCustomResource is the Schema for the mycustomresources API
type MyCustomResource struct {
 metav1.TypeMeta   `json:",inline"`
 metav1.ObjectMeta `json:"metadata,omitempty"`

 Spec   MyCustomResourceSpec   `json:"spec,omitempty"`
 Status MyCustomResourceStatus `json:"status,omitempty"`
}

// +kubebuilder:object:root=true
// +kubebuilder:subresource:status

// MyCustomResourceList contains a list of MyCustomResource
type MyCustomResourceList struct {
 metav1.TypeMeta `json:",inline"`
 metav1.ListMeta `json:"metadata,omitempty"`
 Items           []MyCustomResource `json:"items"`
}

func init() {
 SchemeBuilder.Register(&MyCustomResource{}, &MyCustomResourceList{})
}
// controllers/mycustomresource_controller.go
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
package controllers

import (
 "context"
 "fmt"

 "github.com/yourusername/my-operator/api/v1"
 "sigs.k8s.io/controller-runtime/pkg/client"
 "sigs.k8s.io/controller-runtime/pkg/controller"
 "sigs.k8s.io/controller-runtime/pkg/handler"
 "sigs.k8s.io/controller-runtime/pkg/manager"
 "sigs.k8s.io/controller-runtime/pkg/reconcile"
 "sigs.k8s.io/controller-runtime/pkg/source"

 logf "sigs.k8s.io/controller-runtime/pkg/log"
)

var log = logf.Log.WithName("mycustomresource-controller")

// MyCustomResourceReconciler reconciles a MyCustomResource object
type MyCustomResourceReconciler struct {
 client.Client
 Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=myoperator.example.com,resources=mycustomresources,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=myoperator.example.com,resources=mycustomresources/status,verbs=get;update;patch

func (r *MyCustomResourceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
 log.Info("Reconciling MyCustomResource")

 // Fetch the MyCustomResource instance
 instance := &v1.MyCustomResource{}
 err := r.Get(ctx, req.NamespacedName, instance)
 if err != nil {
  return ctrl.Result{}, client.IgnoreNotFound(err)
 }

 // Perform your custom reconciliation logic here
 // ...

 return ctrl.Result{}, nil
}

func (r *MyCustomResourceReconciler) SetupWithManager(mgr manager.Manager) error {
 return ctrl.NewControllerManagedBy(mgr).
  For(&v1.MyCustomResource{}).
  Owns(&appsv1.Deployment{}).
  Complete(r)
}
// pkg/controller/controller.go
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
package controller

import (
 "context"
 "fmt"

 "github.com/yourusername/my-operator/controllers"
 "sigs.k8s.io/controller-runtime/pkg/client"
 "sigs.k8s.io/controller-runtime/pkg/manager"
 logf "sigs.k8s.io/controller-runtime/pkg/log"
 "sigs.k8s.io/controller-runtime/pkg/reconcile"

 myoperatorv1 "github.com/yourusername/my-operator/api/v1"
)

var log = logf.Log.WithName("controller")

// Add creates a new MyCustomResourceController object, initializing it with the given manager and options.
func Add(mgr manager.Manager, opts options.AddOptions) error {
 return ctrl.NewControllerManagedBy(mgr).
  For(&myoperatorv1.MyCustomResource{}).
  Owns(&appsv1.Deployment{}).
  Complete(opts.WithEventRecorder(mgr.GetEventRecorderFor("mycustomresource-controller")))
}
config/kubeconfig

Create a kubeconfig file with the necessary credentials to access your Kubernetes cluster.

This template provides a basic structure for a Kubernetes Operator in Go. You can expand upon this by adding more features, such as custom resources, custom controllers, and additional reconciliation logic.

To learn more about Operator SDK and its features, visit the official documentation: https://sdk.operatorframework.io/docs/building-operators/golang/quickstart/

Second use-case: trying wca with Python

  • Query 2: write a python application to scrap the internet!
  • Output #2;
Creating a web scraping application in Python involves using libraries like 
requests
 for making HTTP requests and 
BeautifulSoup
 from 
bs4
 for parsing HTML content. Here's a basic example of a web scraper that fetches and parses the content of a webpage.

First, install the required libraries:
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
pip install requests beautifulsoup4
# Assisted by watsonx Code Assistant 
# Code generated by WCA@IBM in this programming language is not approved for use in IBM product development.
import requests
from bs4 import BeautifulSoup

def fetch_content(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for HTTP errors
        return response.text
    except requests.RequestException as e:
        print(f"Error fetching the URL: {e}")
        return None

def parse_content(html_content):
    soup = BeautifulSoup(html_content, "html.parser")
    return soup

def main():
    url = "https://example.com"  # Replace with the URL you want to scrape
    html_content = fetch_content(url)

    if html_content:
        soup = parse_content(html_content)

        # Example: Extract all paragraph text
        paragraphs = soup.find_all("p")
        for paragraph in paragraphs:
            print(paragraph.get_text())

if __name__ == "__main__":
    main()
This script fetches the content of the specified URL, parses it using BeautifulSoup, and extracts all paragraph text. You can modify the 
parse_content
 function to extract different elements or attributes based on your requirements.

Please note that web scraping should be done responsibly and in compliance with the target website's terms of service and robots.txt file. Some websites may not allow scraping, and doing so could result in legal consequences.

For more advanced web scraping tasks, consider using libraries like 
Scrapy
 or 
Selenium
. These libraries provide more features and better handling of complex web pages, JavaScript rendering, and session management.

Nice, to be tested… 🍺

Third use-case: code explanation!

  • Query for code explanation.
Provide an explanation for the following code;
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{

 // Read image
 Mat im = imread( "blob.jpg", IMREAD_GRAYSCALE );

 // Setup SimpleBlobDetector parameters.
 SimpleBlobDetector::Params params;

 // Change thresholds
 params.minThreshold = 10;
 params.maxThreshold = 200;

 // Filter by Area.
 params.filterByArea = true;
 params.minArea = 1500;

 // Filter by Circularity
 params.filterByCircularity = true;
 params.minCircularity = 0.1;

 // Filter by Convexity
 params.filterByConvexity = true;
 params.minConvexity = 0.87;

 // Filter by Inertia
 params.filterByInertia = true;
 params.minInertiaRatio = 0.01;


 // Storage for blobs
 vector<KeyPoint> keypoints;


#if CV_MAJOR_VERSION < 3   // If you are using OpenCV 2

 // Set up detector with params
 SimpleBlobDetector detector(params);

 // Detect blobs
 detector.detect( im, keypoints);
#else 

 // Set up detector with params
 Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params);   

 // Detect blobs
 detector->detect( im, keypoints);
#endif 

 // Draw detected blobs as red circles.
 // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
 // the size of the circle corresponds to the size of blob

 Mat im_with_keypoints;
 drawKeypoints( im, keypoints, im_with_keypoints, Scalar(0,0,255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS );

 // Show blobs
 imshow("keypoints", im_with_keypoints );
 waitKey(0);

}

The output 🚀

This C++ code is a simple example of using OpenCV's 
SimpleBlobDetector
 to detect blobs (regions of interest) in a grayscale image. Here's a breakdown of the code:

Include the OpenCV header file: 
#include "opencv2/opencv.hpp"
Declare the 
cv
 and 
std
 namespaces: 
using namespace cv;
 and 
using namespace std;
.
Define the 
main
 function, which is the entry point of the program.
Read an image named "blob.jpg" in grayscale mode using 
imread
: 
Mat im = imread("blob.jpg", IMREAD_GRAYSCALE);
.
Create a 
SimpleBlobDetector::Params
 object named 
params
 to store the detection parameters.
Set the minimum and maximum thresholds for blob detection: 
params.minThreshold = 10;
 and 
params.maxThreshold = 200;
.
Enable filtering by area, circularity, convexity, and inertia, and set their respective thresholds:
params.filterByArea = true;
 and 
params.minArea = 1500;
params.filterByCircularity = true;
 and 
params.minCircularity = 0.1;
params.filterByConvexity = true;
 and 
params.minConvexity = 0.87;
params.filterByInertia = true;
 and 
params.minInertiaRatio = 0.01;
Create a vector named 
keypoints
 to store the detected blobs' keypoints.
Set up the 
SimpleBlobDetector
 with the given parameters. The code uses conditional compilation (
#if CV_MAJOR_VERSION < 3
) to handle differences between OpenCV 2 and OpenCV 3.
Detect blobs in the image and store the keypoints in the 
keypoints
 vector.
Create a new image named 
im_with_keypoints
 to display the original image with detected blobs as red circles.
Use the 
drawKeypoints
 function to draw the detected blobs as red circles on the new image.
Display the image with detected blobs using 
imshow
.
Wait for a key press before closing the window with 
waitKey(0)
.
This code demonstrates how to use OpenCV's 
SimpleBlobDetector
 to detect blobs in an image based on specific parameters. You can modify the parameters to suit your needs and apply this technique to various images and use cases.

I love this tool ❤️‍🔥🎇

Conclusion

In this brief exploration, we’ve touched upon the exciting potential of watsonx Code Assistant as a versatile AI companion for a wide range of programming tasks. Its ability to offer context-aware assistance within your IDE holds significant promise for boosting developer productivity and simplifying the coding experience across numerous popular languages. I trust this initial overview has provided a helpful glimpse into its general capabilities and sparked your interest in leveraging this innovative technology.

Looking ahead, I’m eager to delve deeper into the specialized applications of watsonx Code Assistant. In an upcoming post, I’ll focus specifically on its capabilities for Ansible, highlighting how it can enhance and augment operational activities.

Stay tuned to discover how this intelligent assistant can streamline your automation workflows and bring a new level of efficiency to your operations teams.

Links