Skip to main content
This will help you get started with IBM text completion models (LLMs) using LangChain. For detailed documentation on IBM watsonx.ai features and configuration options, please refer to the IBM watsonx.ai.

Overview

Integration details

ClassPackageLocalSerializablePY supportDownloadsVersion
WatsonxLLM@langchain/ibmNPM - DownloadsNPM - Version

Setup

To access IBM WatsonxAI models you’ll need to create an IBM watsonx.ai account, get an API key or any other type of credentials, and install the @langchain/ibm integration package.

Credentials

Head to IBM Cloud to sign up to IBM watsonx.ai and generate an API key or provide any other authentication form as presented below.

IAM authentication

Bearer token authentication

IBM watsonx.ai software authentication

Once these are placed in your environment variables and object is initialized authentication will proceed automatically. Authentication can also be accomplished by passing these values as parameters to a new instance.

IAM authentication

Bearer token authentication

IBM watsonx.ai software authentication

If you want to get automated tracing of your model calls you can also set your LangSmith API key by uncommenting below:

Installation

The LangChain IBM watsonx.ai integration lives in the @langchain/ibm package:

Instantiation

Now we can instantiate our model object and generate chat completions:
Note:
  • You must provide spaceId, projectId or idOrName(deployment id) unless you use lightweight engine which works without specifying either (refer to watsonx.ai docs)
  • Depending on the region of your provisioned service instance, use correct serviceUrl.
  • You need to specify the model you want to use for inferencing through model_id.

Using model Gateway

To use model gateway with Langchain, you need to previously create a provider and add model via @ibm-cloud/watsonx-ai SDK or watsonx.ai API. Follow this documentation:

Invocation and generation

Chaining

We can chain our completion model with a prompt template like so:

Props overwriting

Passed props at initialization will last for the whole life cycle of the object, however you may overwrite them for a single method’s call by passing second argument as below

Tokenization

This package has it’s custom getNumTokens implementation which returns exact amount of tokens that would be used.

API reference

For detailed documentation of all IBM watsonx.ai features and configurations head to the API reference: API docs