WatsonxToolkit은 IBM watsonx.ai Toolkit의 wrapper입니다.
이 예제는 LangChain을 사용하여 watsonx.ai Toolkit을 사용하는 방법을 보여줍니다.

개요

Integration 세부 정보

ClassPackageSerializableJS supportDownloadsVersion
WatsonxToolkitlangchain-ibmPyPI - DownloadsPyPI - Version

설정

IBM watsonx.ai toolkit에 액세스하려면 IBM watsonx.ai 계정을 생성하고, API key를 받고, langchain-ibm integration package를 설치해야 합니다.

자격 증명

이 셀은 watsonx Toolkit을 사용하는 데 필요한 WML 자격 증명을 정의합니다. 작업: IBM Cloud 사용자 API key를 제공하세요. 자세한 내용은 문서를 참조하세요.
import os
from getpass import getpass

watsonx_api_key = getpass()
os.environ["WATSONX_APIKEY"] = watsonx_api_key
추가로 환경 변수로 추가 secrets를 전달할 수 있습니다.
import os

os.environ["WATSONX_URL"] = "your service instance url"
os.environ["WATSONX_TOKEN"] = "your token for accessing the CLOUD or CPD cluster"
os.environ["WATSONX_PASSWORD"] = "your password for accessing the CPD cluster"
os.environ["WATSONX_USERNAME"] = "your username for accessing the CPD cluster"
os.environ["WATSONX_INSTANCE_ID"] = "your instance_id for accessing the CPD cluster"

설치

LangChain IBM integration은 langchain-ibm package에 있습니다:
!pip install -qU langchain-ibm

인스턴스화

WatsonxToolkit class를 초기화합니다.
from langchain_ibm.agent_toolkits.utility import WatsonxToolkit

watsonx_toolkit = WatsonxToolkit(
    url="https://us-south.ml.cloud.ibm.com",
)
또는 Cloud Pak for Data 자격 증명을 사용할 수 있습니다. 자세한 내용은 watsonx.ai software setup을 참조하세요. 특정 요구 사항의 경우, IBM의 APIClient 객체를 WatsonxToolkit class에 전달하는 옵션이 있습니다.
from ibm_watsonx_ai import APIClient

api_client = APIClient(...)

watsonx_toolkit = WatsonxToolkit(
    watsonx_client=api_client,
)

Tools

모든 tools 가져오기

사용 가능한 모든 tools를 WatsonxTool 객체의 list로 가져올 수 있습니다.
watsonx_toolkit.get_tools()
사용 가능한 tools의 list는 IBM Cloud용 IBM watsonx.ai인지 IBM watsonx.ai software인지에 따라 다를 수 있습니다.
[WatsonxTool(name='GoogleSearch', description='Search for online trends, news, current events, real-time information, or research topics.', args_schema=<class 'langchain_ibm.toolkit.ToolArgsSchema'>, agent_description='Search for online trends, news, current events, real-time information, or research topics.', tool_config_schema={'title': 'config schema for GoogleSearch tool', 'type': 'object', 'properties': {'maxResults': {'title': 'Max number of results to return', 'type': 'integer', 'minimum': 1, 'maximum': 20}}}, watsonx_client=<ibm_watsonx_ai.client.APIClient object at 0x127e0f490>),
 WatsonxTool(name='WebCrawler', description='Useful for when you need to summarize a webpage. Do not use for Web search.', args_schema=<class 'langchain_ibm.toolkit.ToolArgsSchema'>, agent_description='Useful for when you need to summarize a webpage. Do not use for Web search.', tool_input_schema={'type': 'object', 'properties': {'url': {'title': 'url', 'description': 'URL for the webpage to be scraped', 'type': 'string', 'pattern': '^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$'}}, 'required': ['url']}, watsonx_client=<ibm_watsonx_ai.client.APIClient object at 0x127e0f490>),
 WatsonxTool(name='SDXLTurbo', description='Generate an image from text using Stability.ai', args_schema=<class 'langchain_ibm.toolkit.ToolArgsSchema'>, agent_description='Generate an image from text. Not for image refining. Use very precise language about the desired image, including setting, lighting, style, filters and lenses used. Do not ask the tool to refine an image.', watsonx_client=<ibm_watsonx_ai.client.APIClient object at 0x127e0f490>),
 WatsonxTool(name='Weather', description='Find the weather for a city.', args_schema=<class 'langchain_ibm.toolkit.ToolArgsSchema'>, agent_description='Find the weather for a city.', tool_input_schema={'type': 'object', 'properties': {'location': {'title': 'location', 'description': 'Name of the location', 'type': 'string'}, 'country': {'title': 'country', 'description': 'Name of the state or country', 'type': 'string'}}, 'required': ['location']}, watsonx_client=<ibm_watsonx_ai.client.APIClient object at 0x127e0f490>),
 WatsonxTool(name='RAGQuery', description='Search the documents in a vector index.', args_schema=<class 'langchain_ibm.toolkit.ToolArgsSchema'>, agent_description='Search information in documents to provide context to a user query. Useful when asked to ground the answer in specific knowledge about {indexName}', tool_config_schema={'title': 'config schema for RAGQuery tool', 'type': 'object', 'properties': {'vectorIndexId': {'title': 'Vector index identifier', 'type': 'string'}, 'projectId': {'title': 'Project identifier', 'type': 'string'}, 'spaceId': {'title': 'Space identifier', 'type': 'string'}}, 'required': ['vectorIndexId'], 'oneOf': [{'required': ['projectId']}, {'required': ['spaceId']}]}, watsonx_client=<ibm_watsonx_ai.client.APIClient object at 0x127e0f490>)]

Tool 가져오기

이름으로 특정 WatsonxTool을 가져올 수도 있습니다.
google_search = watsonx_toolkit.get_tool(tool_name="GoogleSearch")

호출

간단한 input으로 tool 호출하기

search_result = google_search.invoke({"q": "IBM"})
search_result
{'output': '[{"title":"IBM - United States","description":"Technology & Consulting. From next-generation AI to cutting edge hybrid cloud solutions to the deep expertise of IBM Consulting, IBM has what it takes to help\xa0...","url":"https://www.ibm.com/us-en"},{"title":"IBM - Wikipedia","description":"International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in\xa0...","url":"https://en.wikipedia.org/wiki/IBM"},{"title":"IBM Envizi ESG Suite","description":"Envizi systemizes the capture, transformation and consolidation of disparate sustainability data into a single source of truth and delivers actionable insights.","url":"https://www.ibm.com/products/envizi"},{"title":"IBM Research","description":"Tools + Code · BeeAI Framework. Open-source framework for building, deploying, and serving powerful agentic workflows at scale. · Docling. An open-source tool\xa0...","url":"https://research.ibm.com/"},{"title":"IBM SkillsBuild: Free Skills-Based Learning From Technology Experts","description":"IBM SkillsBuildPower your future in tech with job skills, courses, and credentials—for free. Power your future in tech with job skills, courses, and credentials\xa0...","url":"https://skillsbuild.org/"},{"title":"IBM | LinkedIn","description":"Locations · Primary. International Business Machines Corp. · 590 Madison Ave · 90 Grayston Dr · Plaza Independencia 721 · 388 Phahon Yothin Road · Jalan Prof.","url":"https://www.linkedin.com/company/ibm"},{"title":"International Business Machines Corporation (IBM)","description":"PROFITABILITY_AND_INCOME_STATEMENT · 9.60% · (TTM). 3.06% · (TTM). 24.06% · (TTM). 62.75B · (TTM). 6.02B · (TTM). 6.41. BALANCE_SHEET_AND_CASH_FLOW. (MRQ).","url":"https://finance.yahoo.com/quote/IBM/"},{"title":"Zurich - IBM Research","description":"The location in Zurich is one of IBM\'s 12 global research labs. IBM has maintained a research laboratory in Switzerland since 1956.","url":"https://research.ibm.com/labs/zurich"},{"title":"IBM (@ibm) • Instagram photos and videos","description":"Science, Technology & Engineering. We partner with developers, data scientists, CTOs and other creators to make the world work better.","url":"https://www.instagram.com/ibm/?hl=en"},{"title":"IBM Newsroom","description":"News and press releases from around the IBM world. Media contacts. Sources by topic and by region. IBM Media center. Explore IBM\'s latest and most popular\xa0...","url":"https://newsroom.ibm.com/"}]'}
받은 결과의 list를 가져오려면 아래 셀을 실행할 수 있습니다.
import json

output = json.loads(search_result.get("output"))
output

구성과 함께 tool 호출하기

tool에 config schema가 있는지 확인하고 해당 속성을 보려면 tool의 tool_config_schema를 확인할 수 있습니다. 이 예제에서 tool은 반환할 최대 결과 수를 설정하는 maxResults parameter를 포함하는 config schema를 가지고 있습니다.
google_search.tool_config_schema
{'title': 'config schema for GoogleSearch tool',
 'type': 'object',
 'properties': {'maxResults': {'title': 'Max number of results to return',
   'type': 'integer',
   'minimum': 1,
   'maximum': 20}}}
tool_config parameters를 설정하려면 set_tool_config() method를 사용하고 위의 tool_config_schema에 따라 올바른 dict를 전달해야 합니다.
import json

config = {"maxResults": 3}
google_search.set_tool_config(config)

search_result = google_search.invoke({"q": "IBM"})
output = json.loads(search_result.get("output"))
최대 3개의 결과가 있어야 합니다.
print(len(output))
3

Input schema와 함께 tool 호출하기

예제 목적으로 다른 tool(input schema가 있는)을 가져와야 합니다.
weather_tool = watsonx_toolkit.get_tool("Weather")
tool에 input schema가 있는지 확인하고 해당 속성을 보려면 tool의 tool_input_schema를 확인할 수 있습니다. 이 예제에서 tool은 하나의 필수 parameter와 하나의 선택적 parameter를 포함하는 input schema를 가지고 있습니다.
weather_tool.tool_input_schema
{'type': 'object',
 'properties': {'location': {'title': 'location',
   'description': 'Name of the location',
   'type': 'string'},
  'country': {'title': 'country',
   'description': 'Name of the state or country',
   'type': 'string'}},
 'required': ['location']}
invoke()에 input을 올바르게 전달하려면 필수 parameter를 key로 하고 그 값을 가진 invoke_input dictionary를 생성해야 합니다.
invoke_input = {
    "location": "New York",
}

weather_result = weather_tool.invoke(input=invoke_input)
weather_result
{'output': 'Current weather in New York:\nTemperature: 0°C\nRain: 0mm\nRelative humidity: 63%\nWind: 7.6km/h\n'}
이번에는 output이 단일 문자열 값입니다. 이를 가져와서 출력하려면 아래 셀을 실행할 수 있습니다.
output = weather_result.get("output")
print(output)
Current weather in New York:
Temperature: 0°C
Rain: 0mm
Relative humidity: 63%
Wind: 7.6km/h

ToolCall로 tool 호출하기

ToolCall로 tool을 호출할 수도 있으며, 이 경우 ToolMessage가 반환됩니다:
invoke_input = {
    "location": "Los Angeles",
}
tool_call = dict(
    args=invoke_input,
    id="1",
    name=weather_tool.name,
    type="tool_call",
)
weather_tool.invoke(input=tool_call)
ToolMessage(content='{"output": "Current weather in Los Angeles:\\nTemperature: 8.6°C\\nRain: 0mm\\nRelative humidity: 61%\\nWind: 8.4km/h\\n"}', name='Weather', tool_call_id='1')

Agent 내에서 사용하기

from langchain_ibm import ChatWatsonx

llm = ChatWatsonx(
    model_id="meta-llama/llama-3-3-70b-instruct",
    url="https://us-south.ml.cloud.ibm.com",
    project_id="PASTE YOUR PROJECT_ID HERE",
)
from langchain.agents import create_agent


tools = [weather_tool]
agent = create_agent(llm, tools)
example_query = "What is the weather in Boston?"

events = agent.stream(
    {"messages": [("user", example_query)]},
    stream_mode="values",
)
for event in events:
    event["messages"][-1].pretty_print()
================================ Human Message =================================

What is the weather in Boston?
================================== Ai Message ==================================
Tool Calls:
  Weather (chatcmpl-tool-6a6c21402c824e43bdd2e8ba390af4a8)
 Call ID: chatcmpl-tool-6a6c21402c824e43bdd2e8ba390af4a8
  Args:
    location: Boston
================================= Tool Message =================================
Name: Weather

{"output": "Current weather in Boston:\nTemperature: -1°C\nRain: 0mm\nRelative humidity: 53%\nWind: 8.3km/h\n"}
================================== Ai Message ==================================

The current weather in Boston is -1°C with 0mm of rain, a relative humidity of 53%, and a wind speed of 8.3km/h.

API reference

모든 WatsonxToolkit 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I