Path: blob/master/cloud/notebooks/python_sdk/deployments/foundation_models/Use watsonx, and LangChain to make a series of calls to a language model.ipynb
9484 views

Use watsonx, and LangChain to make a series of calls to a language model
Disclaimers
Use only Projects and Spaces that are available in watsonx context.
Notebook content
This notebook contains the steps and code to demonstrate Sequential Chain using langchain integration with watsonx models.
Some familiarity with Python is helpful. This notebook uses Python 3.12.
Learning goal
The goal of this notebook is to demonstrate how to chain mistral-small-3-1-24b-instruct-2503 and mistral-medium-2505 models to generate a sequence of creating a random question on a given topic and an answer to that question and also to make the user friends with LangChain framework, using simple chain (LLMChain) and the extended chain (SequentialChain) with the WatsonxLLM.
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:
Create a watsonx.ai Runtime Service instance (a free plan is offered and information about how to create the instance can be found here).
Install and import dependencies
Note: ibm-watsonx-ai documentation can be found here.
Successfully installed PyYAML-6.0.3 SQLAlchemy-2.0.45 annotated-types-0.7.0 anyio-4.12.1 certifi-2026.1.4 charset_normalizer-3.4.4 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 idna-3.11 jsonpatch-1.33 jsonpointer-3.0.0 langchain-0.3.27 langchain-core-0.3.83 langchain-text-splitters-0.3.11 langsmith-0.6.3 orjson-3.11.5 pydantic-2.12.5 pydantic-core-2.41.5 requests-2.32.5 requests-toolbelt-1.0.0 tenacity-9.1.2 typing-extensions-4.15.0 typing-inspection-0.4.2 urllib3-2.6.3 uuid-utils-0.13.0 zstandard-0.25.0
Successfully installed cachetools-6.2.4 ibm-cos-sdk-2.14.3 ibm-cos-sdk-core-2.14.3 ibm-cos-sdk-s3transfer-2.14.3 ibm-watsonx-ai-1.5.0 jmespath-1.0.1 langchain_ibm-0.3.20 lomond-0.3.3 numpy-2.4.1 pandas-2.2.3 pytz-2025.2 tabulate-0.9.0 tzdata-2025.3
Defining the watsonx.ai credentials
This cell defines the watsonx.ai credentials required to work with watsonx Foundation Model inferencing.
Action: Provide the IBM Cloud user API key. For details, see documentation.
Working with spaces
You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.
Click New Deployment Space
Create an empty space
Select Cloud Object Storage
Select watsonx.ai Runtime instance and press Create
Go to Manage tab
Copy
Space GUIDand 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
Create an instance of APIClient with authentication details.
List available models
All avaliable models are presented under TextModels class.
You need to specify model_id's that will be used for inferencing:
Defining the model parameters
You might need to adjust model parameters for different models or tasks, to do so please refer to documentation under GenTextParamsMetaNames class.
Action: If any complications please refer to the documentation.
LangChain integration
WatsonxLLM is a wrapper around watsonx.ai models that provide chain integration around the models.
Action: For more details about CustomLLM check the LangChain documentation
Initialize the WatsonxLLM class.
You can print all set data about the WatsonxLLM object using the dict() method.
Sequential Chain experiment
The simplest type of sequential chain is called a SequentialChain, in which each step has a single input and output and the output of one step serves as the input for the following step.
The experiment will consist in generating a random question about any topic and answer the following question.
An object called PromptTemplate assists in generating prompts using a combination of user input, additional non-static data, and a fixed template string.
In our case we would like to create two PromptTemplate objects which will be responsible for creating a random question and answering it.
In the chain below, prompt_1 is passed to mistral_small_llm, then its response is added to prompt_2, which is then passed to mistral_medium_llm, after which we receive the response:
Generate random question and answer to topic.
[chain/start] [chain:RunnableSequence] Entering Chain run with input:
{
"topic": "Formula 1"
}
[chain/start] [chain:RunnableSequence > prompt:PromptTemplate] Entering Prompt run with input:
{
"topic": "Formula 1"
}
[chain/end] [chain:RunnableSequence > prompt:PromptTemplate] [0ms] Exiting Prompt run with output:
[outputs]
[llm/start] [chain:RunnableSequence > llm:WatsonxLLM] Entering LLM run with input:
{
"prompts": [
"Describe a single specific person related to Formula 1. The description must fit only this exact person. Do not use their name anywhere in your response."
]
}
[llm/end] [chain:RunnableSequence > llm:WatsonxLLM] [2.96s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "1960s Formula 1 driver, born in the United Kingdom, who was the first to win a Grand Prix in a car with a rear-mounted engine. The driver was also the first to win a Grand Prix in a car with a monocoque chassis. The driver was the first to win a Grand Prix in a car with a semi-automatic gearbox. The driver was the first to win a Grand Prix in a car with a carbon-fiber chassis. The driver was the first to win a Grand Prix in a car with a turbocharged engine. The driver was the first to win a Grand Prix in a car with a ground-effect aerodynamics. The driver was the first to win a Grand Prix in a car with a carbon-fiber brake discs. The driver was the first to win a Grand Prix in a car with a traction control system. The driver was the first to win a Grand Prix in a car with a carbon-fiber wishbones. The driver",
"generation_info": {
"finish_reason": "max_tokens"
},
"type": "Generation"
}
]
],
"llm_output": {
"token_usage": {
"completion_tokens": 200,
"prompt_tokens": 33,
"total_tokens": 233
},
"model_id": "mistralai/mistral-small-3-1-24b-instruct-2503",
"deployment_id": null
},
"run": null,
"type": "LLMResult"
}
[chain/start] [chain:RunnableSequence > prompt:PromptTemplate] Entering Prompt run with input:
{
"input": "1960s Formula 1 driver, born in the United Kingdom, who was the first to win a Grand Prix in a car with a rear-mounted engine. The driver was also the first to win a Grand Prix in a car with a monocoque chassis. The driver was the first to win a Grand Prix in a car with a semi-automatic gearbox. The driver was the first to win a Grand Prix in a car with a carbon-fiber chassis. The driver was the first to win a Grand Prix in a car with a turbocharged engine. The driver was the first to win a Grand Prix in a car with a ground-effect aerodynamics. The driver was the first to win a Grand Prix in a car with a carbon-fiber brake discs. The driver was the first to win a Grand Prix in a car with a traction control system. The driver was the first to win a Grand Prix in a car with a carbon-fiber wishbones. The driver"
}
[chain/end] [chain:RunnableSequence > prompt:PromptTemplate] [0ms] Exiting Prompt run with output:
[outputs]
[llm/start] [chain:RunnableSequence > llm:WatsonxLLM] Entering LLM run with input:
{
"prompts": [
"1960s Formula 1 driver, born in the United Kingdom, who was the first to win a Grand Prix in a car with a rear-mounted engine. The driver was also the first to win a Grand Prix in a car with a monocoque chassis. The driver was the first to win a Grand Prix in a car with a semi-automatic gearbox. The driver was the first to win a Grand Prix in a car with a carbon-fiber chassis. The driver was the first to win a Grand Prix in a car with a turbocharged engine. The driver was the first to win a Grand Prix in a car with a ground-effect aerodynamics. The driver was the first to win a Grand Prix in a car with a carbon-fiber brake discs. The driver was the first to win a Grand Prix in a car with a traction control system. The driver was the first to win a Grand Prix in a car with a carbon-fiber wishbones. The driver The previous text describes a person. Their name is:"
]
}
[llm/end] [chain:RunnableSequence > llm:WatsonxLLM] [793ms] Exiting LLM run with output:
{
"generations": [
[
{
"text": "1960s Formula 1 driver, born in the United Kingdom, who was the first",
"generation_info": {
"finish_reason": "max_tokens"
},
"type": "Generation"
}
]
],
"llm_output": {
"token_usage": {
"completion_tokens": 20,
"prompt_tokens": 213,
"total_tokens": 233
},
"model_id": "mistralai/mistral-medium-2505",
"deployment_id": null
},
"run": null,
"type": "LLMResult"
}
[chain/end] [chain:RunnableSequence] [3.75s] Exiting Chain run with output:
{
"output": "1960s Formula 1 driver, born in the United Kingdom, who was the first"
}
Function implementation.
Let's wrap the above chain code into function.
Test the function
It is good practice to validate the code locally first.
Store the function
Create online deployment
Summary and next steps
You successfully completed this notebook!
You learned how to use Sequential Chain using custom llm WastonxLLM.
Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.
Authors:
Lukasz Cmielowski, PhD, Senior Technical Staff Member at watsonx.ai.
Mateusz Szewczyk, Software Engineer at watsonx.ai.
Copyright © 2024-2026 IBM. This notebook and its source code are released under the terms of the MIT License.