Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cpd5.1/notebooks/python_sdk/deployments/ai_services/Use watsonx, and `granite-3-8b-instruct` to run as an AI service.ipynb
6405 views
Kernel: watsonx-ai-samples-py-3-11

image

Use watsonx, and ibm/granite-3-8b-instruct to run as an AI service

Disclaimers

  • Use only Projects and Spaces that are available in watsonx context.

Notebook content

This notebook provides a detailed demonstration of the steps and code required to showcase support for watsonx.ai AI service.

Some familiarity with Python is helpful. This notebook uses Python 3.11.

Learning goal

The learning goal for your notebook is to leverage AI services to generate accurate and contextually relevant responses based on a question.

Table of Contents

This notebook contains the following parts:

Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Contact with your Cloud Pak for Data administrator and ask them for your account credentials

Install dependencies

%pip install -U "ibm_watsonx_ai>=1.2.4" | tail -n 1
Successfully installed ibm_watsonx_ai-1.2.4

Define credentials

Authenticate the Watson Machine Learning service on IBM Cloud Pak for Data. You need to provide the admin's username and the platform url.

username = "PASTE YOUR USERNAME HERE" url = "PASTE THE PLATFORM URL HERE"

Use the admin's api_key to authenticate WML services:

import getpass from ibm_watsonx_ai import Credentials credentials = Credentials( username=username, api_key=getpass.getpass("Enter your watsonx.ai API key and hit enter: "), url=url, instance_id="openshift", version="5.1" )

Alternatively you can use the admin's password:

import getpass from ibm_watsonx_ai import Credentials credentials = Credentials( username=username, password=getpass.getpass("Enter your watsonx.ai password and hit enter: "), url=url, instance_id="openshift", version="5.1" )

Working with spaces

First of all, you need to create a space that will be used for your work. If you do not have a space, you can use {PLATFORM_URL}/ml-runtime/spaces?context=icp4data to create one.

  • Click New Deployment Space

  • Create an empty space

  • Go to space Settings tab

  • Copy space_id and paste it below

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: Assign space ID below

space_id = "PASTE YOUR SPACE ID HERE"

Create APIClient instance

from ibm_watsonx_ai import APIClient api_client = APIClient(credentials, space_id=space_id)

Specify model

This notebook uses chat model ibm/granite-3-8b-instruct, which has to be available on your Cloud Pak for Data environment for this notebook to run successfully. If this model is not available on your Cloud Pack for Data environment, you can specify any other available chat model. You can list available chat models by running the cell below.

if len(api_client.foundation_models.ChatModels): print(*api_client.foundation_models.ChatModels, sep="\n") else: print("Chat models are missing in this environment. Install chat models to proceed.")
ibm/granite-3-8b-instruct

Specify the model_id of the model you will use for the chat.

model_id = "ibm/granite-3-8b-instruct"

Create AI service

Prepare function which will be deployed using AI service.

Please specify the default parameters that will be passed to the function.

def deployable_ai_service(context, space_id=space_id, url=credentials["url"], model_id=model_id, params={"temperature": 1}, **kwargs): from ibm_watsonx_ai import APIClient, Credentials from ibm_watsonx_ai.foundation_models import ModelInference api_client = APIClient( credentials=Credentials( url=url, token=context.generate_token(), instance_id="openshift", ), space_id=space_id, ) model = ModelInference( model_id=model_id, api_client=api_client, params=params, ) def generate(context) -> dict: api_client.set_token(context.get_token()) payload = context.get_json() question = payload["question"] messages = [ { "role": "system", "content": "You are a helpful assistant.", }, { "role": "user", "content": question } ] response = model.chat(messages=messages) return { "body": response } def generate_stream(context): api_client.set_token(context.get_token()) payload = context.get_json() question = payload["question"] messages = [ { "role": "system", "content": "You are a helpful assistant.", }, { "role": "user", "content": question } ] yield from model.chat_stream(messages) return generate, generate_stream

Testing AI service's function locally

You can test AI service's function locally. Initialize RuntimeContext firstly.

from ibm_watsonx_ai.deployments import RuntimeContext context = RuntimeContext(api_client=api_client)
local_function = deployable_ai_service(context=context)

Prepare request json payload for local invoke.

context.request_payload_json = {"question": "When was IBM founded?"}

Execute the generate function locally.

resp = local_function[0](context) resp
{'body': {'id': 'chatcmpl-386d2db6-2fc1-4b4d-808c-a8cbfe0458c8', 'model_id': 'ibm/granite-3-8b-instruct', 'model': 'ibm/granite-3-8b-instruct', 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'IBM was officially incorporated on June 16, 1911. However, it traces its roots back to 1906 when the "$5,000 doorbell" made by the Computing-Tabulating-Recording Company (CTR) attracted the attention of major banks and railroads. IBM evolved from CTR, which was founded by Charles Ranlett Flint, to become a leading technology company.'}, 'finish_reason': 'stop'}], 'created': 1741254013, 'model_version': '1.0.0', 'created_at': '2025-03-06T09:40:14.877Z', 'usage': {'completion_tokens': 98, 'prompt_tokens': 25, 'total_tokens': 123}, 'system': {'warnings': [{'message': "The value of 'max_tokens' for this model was set to value 1024", 'id': 'unspecified_max_token', 'additional_properties': {'limit': 0, 'new_value': 1024, 'parameter': 'max_tokens', 'value': 0}}]}}}

Execute the generate_stream function locally.

response = local_function[1](context)
for chunk in response: if chunk["choices"]: print(chunk["choices"][0]["delta"].get("content", ""), end="", flush=True)
IBM, an American multinational information technology company, was established on June 16, 1911. It was originally called Computing-Tabulating-Recording Company (CTR), before adopting its present name, International Business Machines, in 1924.

Deploy AI service

Store AI service with previous created custom software specifications.

sw_spec_id = api_client.software_specifications.get_id_by_name("runtime-24.1-py3.11") sw_spec_id
'45f12dfe-aa78-5b8d-9f38-0ee223c47309'
meta_props = { api_client.repository.AIServiceMetaNames.NAME: "AI service with SDK", api_client.repository.AIServiceMetaNames.SOFTWARE_SPEC_ID: sw_spec_id } stored_ai_service_details = api_client.repository.store_ai_service(deployable_ai_service, meta_props)
ai_service_id = api_client.repository.get_ai_service_id(stored_ai_service_details) ai_service_id
'bf74d772-f259-47ec-9545-7adbc8d08cd2'

Create online deployment of AI service.

meta_props = { api_client.deployments.ConfigurationMetaNames.NAME: "AI service with SDK", api_client.deployments.ConfigurationMetaNames.ONLINE: {}, } deployment_details = api_client.deployments.create(ai_service_id, meta_props)
###################################################################################### Synchronous deployment creation for id: 'bf74d772-f259-47ec-9545-7adbc8d08cd2' started ###################################################################################### initializing Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead. ....... ready ----------------------------------------------------------------------------------------------- Successfully finished deployment creation, deployment_id='90266394-4ed8-421b-9b86-48aabefcf9b9' -----------------------------------------------------------------------------------------------

Obtain the deployment_id of the previously created deployment.

deployment_id = api_client.deployments.get_id(deployment_details)

Example of Executing an AI service.

Execute generate method.

question = "When was IBM founded?" deployments_results = api_client.deployments.run_ai_service( deployment_id, {"question": question} )
import json print(json.dumps(deployments_results, indent=2))
{ "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "IBM was founded on June 16, 1911. It was originally called Computing-Tabulating-Recording Company (CTR), which later was renamed to International Business Machines in 1924.", "role": "assistant" } } ], "created": 1741254247, "created_at": "2025-03-06T09:44:08.186Z", "id": "chatcmpl-3b60a014-9277-4574-97d8-5d1796a64e0b", "model": "ibm/granite-3-8b-instruct", "model_id": "ibm/granite-3-8b-instruct", "model_version": "1.0.0", "system": { "warnings": [ { "additional_properties": { "limit": 0, "new_value": 1024, "parameter": "max_tokens", "value": 0 }, "id": "unspecified_max_token", "message": "The value of 'max_tokens' for this model was set to value 1024" } ] }, "usage": { "completion_tokens": 47, "prompt_tokens": 25, "total_tokens": 72 } }

Execute generate_stream method.

question = "When was IBM founded?" deployments_results = api_client.deployments.run_ai_service_stream( deployment_id, {"question": question} )
import json for chunk in deployments_results: chunk_json = json.loads(chunk) if chunk_json["choices"]: print(chunk_json["choices"][0]["delta"].get("content", ""), end="", flush=True)
IBM, or International Business Machines Corporation, was established on June 16, 1911. It was initially founded as the Computing-Tabulating-Recording Company (CTR), which was a consolidation of several enterprises operating in the USA. The name was changed to International Business Machines Corporation in 1924. IBM has since become a significant player in the global technology industry, contributing to numerous technological advancements across sectors such as computer hardware, software, and services.

Summary and next steps

You successfully completed this notebook!

You learned how to create and deploy AI service using ibm_watsonx_ai SDK.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Author

Rafał Chrzanowski, Software Engineer Intern at watsonx.ai.

Copyright © 2025 IBM. This notebook and its source code are released under the terms of the MIT License.