> ## Documentation Index
> Fetch the complete documentation index at: https://docs.langchain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# IBM watsonx.ai integration

> Integrate with the IBM watsonx.ai LLM using LangChain JavaScript.

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](https://reference.langchain.com/javascript/langchain-ibm/WatsonxLLM).

## Overview

### Integration details

| Class                                                                               | Package                                                          | Local | Serializable | [PY support](https://python.langchain.com/docs/integrations/llms/ibm_watsonx/) |                                            Downloads                                           |                                           Version                                           |
| :---------------------------------------------------------------------------------- | :--------------------------------------------------------------- | :---: | :----------: | :----------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------: |
| [`WatsonxLLM`](https://reference.langchain.com/javascript/langchain-ibm/WatsonxLLM) | [`@langchain/ibm`](https://www.npmjs.com/package/@langchain/ibm) |   ❌   |       ✅      |                                        ✅                                       | ![NPM - Downloads](https://img.shields.io/npm/dm/@langchain/ibm?style=flat-square\&label=%20&) | ![NPM - Version](https://img.shields.io/npm/v/@langchain/ibm?style=flat-square\&label=%20&) |

## 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](https://cloud.ibm.com/login) to sign up to IBM watsonx.ai and generate an API key or provide any other authentication form as presented below.

#### IAM authentication

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export WATSONX_AI_AUTH_TYPE=iam
export WATSONX_AI_APIKEY=<YOUR-APIKEY>
```

#### Bearer token authentication

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export WATSONX_AI_AUTH_TYPE=bearertoken
export WATSONX_AI_BEARER_TOKEN=<YOUR-BEARER-TOKEN>
```

#### IBM watsonx.ai software authentication

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export WATSONX_AI_AUTH_TYPE=cp4d
export WATSONX_AI_USERNAME=<YOUR_USERNAME>
export WATSONX_AI_PASSWORD=<YOUR_PASSWORD>
export WATSONX_AI_URL=<URL>
```

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

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { WatsonxLLM } from "@langchain/ibm";

const props = {
  version: "YYYY-MM-DD",
  serviceUrl: "<SERVICE_URL>",
  projectId: "<PROJECT_ID>",
  watsonxAIAuthType: "iam",
  watsonxAIApikey: "<YOUR-APIKEY>",
};
const instance = new WatsonxLLM(props);
```

## Bearer token authentication

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { WatsonxLLM } from "@langchain/ibm";

const props = {
  version: "YYYY-MM-DD",
  serviceUrl: "<SERVICE_URL>",
  projectId: "<PROJECT_ID>",
  watsonxAIAuthType: "bearertoken",
  watsonxAIBearerToken: "<YOUR-BEARERTOKEN>",
};
const instance = new WatsonxLLM(props);
```

### IBM watsonx.ai software authentication

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { WatsonxLLM } from "@langchain/ibm";

const props = {
  version: "YYYY-MM-DD",
  serviceUrl: "<SERVICE_URL>",
  projectId: "<PROJECT_ID>",
  watsonxAIAuthType: "cp4d",
  watsonxAIUsername: "<YOUR-USERNAME>",
  watsonxAIPassword: "<YOUR-PASSWORD>",
  watsonxAIUrl: "<url>",
};
const instance = new WatsonxLLM(props);
```

If you want to get automated tracing of your model calls you can also set your [LangSmith](/langsmith/observability) API key by uncommenting below:

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"
```

### Installation

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

<CodeGroup>
  ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  npm install @langchain/ibm @langchain/core
  ```

  ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/ibm @langchain/core
  ```

  ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pnpm add @langchain/ibm @langchain/core
  ```
</CodeGroup>

## Instantiation

Now we can instantiate our model object and generate chat completions:

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { WatsonxLLM } from "@langchain/ibm";

const props = {
  decoding_method: "sample",
  maxNewTokens: 100,
  minNewTokens: 1,
  temperature: 0.5,
  topK: 50,
  topP: 1,
};
const instance = new WatsonxLLM({
  version: "YYYY-MM-DD",
  serviceUrl: process.env.API_URL,
  projectId: "<PROJECT_ID>",
  // spaceId: "<SPACE_ID>",
  // idOrName: "<DEPLOYMENT_ID>",
  model: "<MODEL_ID>",
  ...props,
});
```

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](https://www.ibm.com/docs/en/cloud-paks/cp-data/5.0.x?topic=install-choosing-installation-mode))
* 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

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { WatsonxLLM } from "@langchain/ibm";

const props = {
  decoding_method: "sample",
  maxNewTokens: 100,
  minNewTokens: 1,
  temperature: 0.5,
  topK: 50,
  topP: 1,
};

const instance = new WatsonxLLM({
  version: "YYYY-MM-DD",
  serviceUrl: process.env.API_URL,
  model: "<MODEL_ID>",
  modelGateway: true,
  ...props,
});
```

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:

* [API](https://cloud.ibm.com/apidocs/watsonx-ai#create-watsonxai-provider).
* [SDK](https://ibm.github.io/watsonx-ai-node-sdk/modules/1_7_x.gateway.html).

## Invocation and generation

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const result = await instance.invoke("Print hello world.");
console.log(result);

const results = await instance.generate([
  "Print hello world.",
  "Print bye, bye world!",
]);
console.log(results);
```

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}

print('Hello world.')<|endoftext|>
{
  generations: [ [ [Object] ], [ [Object] ] ],
  llmOutput: { tokenUsage: { generated_token_count: 28, input_token_count: 10 } }
}
```

## Chaining

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

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { PromptTemplate } from "@langchain/core/prompts"

const prompt = PromptTemplate.fromTemplate("How to say {input} in {output_language}:\n")

const chain = prompt.pipe(instance);
await chain.invoke(
  {
    output_language: "German",
    input: "I love programming.",
  }
)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Ich liebe Programmieren.

To express that you are passionate about programming in German,
```

## 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

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const result2 = await instance.invoke("Print hello world.", {
  parameters: {
    maxNewTokens: 100,
  },
});
console.log(result2);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print('Hello world.')<|endoftext|>
```

## Tokenization

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

```javascript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const tokens = await instance.getNumTokens("Print hello world.");
console.log(tokens);
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
4
```

***

## API reference

For detailed documentation of all `IBM watsonx.ai` features and configurations head to the API reference: [API docs](https://reference.langchain.com/javascript/langchain-ibm/WatsonxLLM)

***

<div className="source-links">
  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>

  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/llms/ibm.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>
</div>
