IBM watsonx.ai 통합

IBM watsonx.ai 통합

LangChain JavaScript로 IBM watsonx.ai 채팅 모델과 통합하는 방법을 안내할게요.

출처: 문서

본문

이 문서는 IBM watsonx.ai 채팅 모델을 시작하는 데 도움을 줘요. 모든 IBM watsonx.ai 기능과 구성에 대한 자세한 문서는 IBM watsonx.ai를 참고하세요.

개요

통합 세부 정보

클래스 패키지 Serializable PY 지원 Downloads Version
ChatWatsonx @langchain/ibm NPM - Downloads NPM - Version

모델 기능

Tool calling Structured output Image input Audio input Video input Token-level streaming Token usage Logprobs

설정

IBM watsonx.ai 모델에 접근하려면 IBM watsonx.ai 계정을 만들고 API 키를 받은 뒤 @langchain/ibm 통합 패키지를 설치해야 해요.

자격 증명

IBM Cloud에서 IBM watsonx.ai에 가입하고 API 키를 생성하거나 아래 제시된 다른 인증 방식을 제공하세요.

IAM 인증

export WATSONX_AI_AUTH_TYPE=iam
export WATSONX_AI_APIKEY=<YOUR-APIKEY>

Bearer 토큰 인증

export WATSONX_AI_AUTH_TYPE=bearertoken
export WATSONX_AI_BEARER_TOKEN=<YOUR-BEARER-TOKEN>

IBM watsonx.ai 소프트웨어 인증

export WATSONX_AI_AUTH_TYPE=cp4d
export WATSONX_AI_USERNAME=<YOUR_USERNAME>
export WATSONX_AI_PASSWORD=<YOUR_PASSWORD>
export WATSONX_AI_URL=<URL>

이 값들이 환경 변수에 들어가고 객체가 초기화되면 인증이 자동으로 진행돼요.

이 값들을 새 인스턴스의 매개변수로 전달해 인증할 수도 있어요.

IAM 인증

import { ChatWatsonx } from "@langchain/ibm";

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

Bearer 토큰 인증

import { ChatWatsonx } from "@langchain/ibm";

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

IBM watsonx.ai 소프트웨어 인증

import { ChatWatsonx } 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 ChatWatsonx(props);

모델 호출의 자동 추적(tracing)을 원한다면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

설치

LangChain IBM watsonx.ai 통합은 @langchain/ibm 패키지에 있어요:

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

인스턴스 생성

이제 모델 객체를 생성하고 채팅 완성을 생성할 수 있어요:

import { ChatWatsonx } from "@langchain/ibm";
const props = {
  maxTokens: 200,
  temperature: 0.5
};

const instance = new ChatWatsonx({
  version: "YYYY-MM-DD",
  serviceUrl: process.env.API_URL,
  projectId: "<PROJECT_ID>",
  // spaceId: "<SPACE_ID>",
  // idOrName: "<DEPLOYMENT_ID>",
  model: "<MODEL_ID>",
  ...props
});

참고:

  • 경량 엔진(lightweight engine)을 사용하지 않는 한 spaceId, projectId 또는 idOrName(배포 ID)을 제공해야 해요 (경량 엔진은 둘 다 지정하지 않고도 동작해요. watsonx.ai 문서 참고)
  • 프로비저닝된 서비스 인스턴스의 리전에 따라 올바른 serviceUrl을 사용하세요.

Model Gateway 사용

import { ChatWatsonx } from "@langchain/ibm";
const props = {
  maxTokens: 200,
  temperature: 0.5
};

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

Langchain으로 모델 게이트웨이를 사용하려면 먼저 @ibm-cloud/watsonx-ai SDK 또는 watsonx.ai API로 제공자(provider)를 생성하고 모델을 추가해야 해요. 다음 문서를 참고하세요:

호출

const aiMsg = await instance.invoke([{
  role: "system",
  content: "You are a helpful assistant that translates English to French. Translate the user sentence.",
},
{
  role: "user",
  content: "I love programming."
}]);
console.log(aiMsg)
AIMessage {
  "id": "chat-c5341b2062dc42f091e5ae2558e905e3",
  "content": " J'adore la programmation.",
  "additional_kwargs": {
    "tool_calls": []
  },
  "response_metadata": {
    "tokenUsage": {
      "completion_tokens": 10,
      "prompt_tokens": 28,
      "total_tokens": 38
    },
    "finish_reason": "stop"
  },
  "tool_calls": [],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 28,
    "output_tokens": 10,
    "total_tokens": 38
  }
}
console.log(aiMsg.content)
 J'adore la programmation.

모델 출력 스트리밍

import { HumanMessage, SystemMessage } from "@langchain/core/messages";

const messages = [
    new SystemMessage('You are a helpful assistant which telling short-info about provided topic.'),
    new HumanMessage("moon")
]
const stream = await instance.stream(messages);
for await(const chunk of stream){
    console.log(chunk)
}
 The
Moon
is
Earth
'
s
 only
natural
 satellite
and

Tool calling

import { tool } from "@langchain/core/tools";
import * as z from "zod";

const calculatorSchema = z.object({
    operation: z
      .enum(["add", "subtract", "multiply", "divide"])
      .describe("The type of operation to execute."),
    number1: z.number().describe("The first number to operate on."),
    number2: z.number().describe("The second number to operate on."),
  });

const calculatorTool = tool(
async ({ operation, number1, number2 }) => {
    if (operation === "add") {
    return `${number1 + number2}`;
    } else if (operation === "subtract") {
    return `${number1 - number2}`;
    } else if (operation === "multiply") {
    return `${number1 * number2}`;
    } else if (operation === "divide") {
    return `${number1 / number2}`;
    } else {
    throw new Error("Invalid operation.");
    }
},
{
    name: "calculator",
    description: "Can perform mathematical operations.",
    schema: calculatorSchema,
}
);

const instanceWithTools = instance.bindTools([calculatorTool]);

const res = await instanceWithTools.invoke("What is 3 * 12");
console.log(res)
AIMessage {
  "id": "chat-d2214d0bdb794483a213b3211cf0d819",
  "content": "",
  "additional_kwargs": {
    "tool_calls": [
      {
        "id": "chatcmpl-tool-257f3d39532141b89178c2120f81f0cb",
        "type": "function",
        "function": "[Object]"
      }
    ]
  },
  "response_metadata": {
    "tokenUsage": {
      "completion_tokens": 38,
      "prompt_tokens": 177,
      "total_tokens": 215
    },
    "finish_reason": "tool_calls"
  },
  "tool_calls": [
    {
      "name": "calculator",
      "args": {
        "number1": 3,
        "number2": 12,
        "operation": "multiply"
      },
      "type": "tool_call",
      "id": "chatcmpl-tool-257f3d39532141b89178c2120f81f0cb"
    }
  ],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 177,
    "output_tokens": 38,
    "total_tokens": 215
  }
}

API 레퍼런스

모든 IBM watsonx.ai 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참고하세요: API 문서


[Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers. [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/chat/ibm.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).

더 알아보기