docs: Add docs for WatsonxToolkit from langchain-ibm (#30340)

**Description:**

Added docs for `WatsonxToolkit` from `langchain-ibm`:
- Sample notebook

Updated provider file: `ibm.mdx`.
This commit is contained in:
Karol Zmorski 2025-03-31 15:18:37 +02:00 committed by GitHub
parent 9213d94057
commit c1acf6f756
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 622 additions and 0 deletions

View File

@ -67,3 +67,13 @@ See a [usage example](/docs/integrations/retrievers/ibm_watsonx_ranker).
```python
from langchain_ibm import WatsonxRerank
```
## Toolkit
### WatsonxToolkit
See a [usage example](/docs/integrations/tools/ibm_watsonx).
```python
from langchain_ibm import WatsonxToolkit
```

View File

@ -0,0 +1,612 @@
{
"cells": [
{
"cell_type": "raw",
"metadata": {},
"source": [
"---\n",
"sidebar_label: IBM watsonx.ai\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# IBM watsonx.ai\n",
"\n",
">WatsonxToolkit is a wrapper for IBM [watsonx.ai](https://www.ibm.com/products/watsonx-ai) Toolkit.\n",
"\n",
"This example shows how to use `watsonx.ai` Toolkit using `LangChain`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overview\n",
"\n",
"### Integration details\n",
"\n",
"| Class | Package | Serializable | [JS support](https://js.langchain.com/docs/integrations/toolkits/ibm/) | Package downloads | Package latest |\n",
"| :--- | :--- | :---: | :---: | :---: | :---: |\n",
"| [WatsonxToolkit](https://python.langchain.com/api_reference/ibm/toolkit/langchain_ibm.toolkit.WatsonxToolkit.html) | [langchain-ibm](https://python.langchain.com/api_reference/ibm/index.html) | ❌ | ✅ | ![PyPI - Downloads](https://img.shields.io/pypi/dm/langchain-ibm?style=flat-square&label=%20) | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-ibm?style=flat-square&label=%20) |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
"\n",
"To access IBM watsonx.ai toolkit you'll need to create an IBM watsonx.ai account, get an API key, and install the `langchain-ibm` integration package.\n",
"\n",
"### Credentials\n",
"\n",
"This cell defines the WML credentials required to work with watsonx Toolkit.\n",
"\n",
"**Action:** Provide the IBM Cloud user API key. For details, see\n",
"[documentation](https://cloud.ibm.com/docs/account?topic=account-userapikey&interface=ui)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from getpass import getpass\n",
"\n",
"watsonx_api_key = getpass()\n",
"os.environ[\"WATSONX_APIKEY\"] = watsonx_api_key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Additionaly you are able to pass additional secrets as an environment variable. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"os.environ[\"WATSONX_URL\"] = \"your service instance url\"\n",
"os.environ[\"WATSONX_TOKEN\"] = \"your token for accessing the service instance\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Installation\n",
"\n",
"The LangChain IBM integration lives in the `langchain-ibm` package:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install -qU langchain-ibm"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Instantiation\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Initialize the `WatsonxToolkit` class.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from langchain_ibm import WatsonxToolkit\n",
"\n",
"watsonx_toolkit = WatsonxToolkit(\n",
" url=\"https://us-south.ml.cloud.ibm.com\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For certain requirements, there is an option to pass the IBM's [`APIClient`](https://ibm.github.io/watsonx-ai-python-sdk/base.html#apiclient) object into the `WatsonxToolkit` class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from ibm_watsonx_ai import APIClient\n",
"\n",
"api_client = APIClient(...)\n",
"\n",
"watsonx_toolkit = WatsonxToolkit(\n",
" watsonx_client=api_client,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tools\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get all tools\n",
"It is possible to get all available tools as a list of `WatsonxTool` objects."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[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>),\n",
" 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>),\n",
" WatsonxTool(name='PythonInterpreter', description='Run Python code generated by the agent model.', args_schema=<class 'langchain_ibm.toolkit.ToolArgsSchema'>, agent_description='Run Python code and return the console output. Use for isolated calculations, computations or data manipulation. In Python, the following modules are available: Use numpy, pandas, scipy and sympy for working with data. Use matplotlib to plot charts. Other Python libraries are also available -- however, prefer using the ones above. Prefer using qualified imports -- `import library; library.thing()` instead of `import thing from library`. Do not attempt to install libraries manually -- it will not work. Do not use this tool multiple times in a row, always write the full code you want to run in a single invocation. If you get an error running Python code, try to generate a better one that will pass. If the tool returns result that starts with IMAGE(, follow instructions for rendering images.', watsonx_client=<ibm_watsonx_ai.client.APIClient object at 0x127e0f490>),\n",
" 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>),\n",
" 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>),\n",
" 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>)]"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"watsonx_toolkit.get_tools()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Get a tool\n",
"You can also get a specific `WatsonxTool` by name."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"google_search = watsonx_toolkit.get_tool(tool_name=\"GoogleSearch\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Invocation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Invoke the tool with a simple input"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'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) Stock Price ...\",\"description\":\"Mar 18, 2025 ... International Business Machines Corporation (IBM) · 1.19% · -2.77% · 11.49% · 12.00% · 29.04% · 138.39% · 3,238.84%. Key Events. Mountain.\",\"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 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/\"},{\"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\"}]'}"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search_result = google_search.invoke(input=\"IBM\")\n",
"search_result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To fetch a list of received results, you can execute the below cell."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"output = json.loads(search_result.get(\"output\"))\n",
"output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Invoke the tool with a configuration"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To check if a tool has a config schema and view its properties you can look at the tool's `tool_config_schema`.\n",
"\n",
"In this example, the tool has a config schema that contains `maxResults` parameter to set maximum number of results to be returned."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'title': 'config schema for GoogleSearch tool',\n",
" 'type': 'object',\n",
" 'properties': {'maxResults': {'title': 'Max number of results to return',\n",
" 'type': 'integer',\n",
" 'minimum': 1,\n",
" 'maximum': 20}}}"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"google_search.tool_config_schema"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To set `tool_config` parameters, you need to use `set_tool_config()` method and pass correct `dict` according to above `tool_config_schema`."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"config = {\"maxResults\": 3}\n",
"google_search.set_tool_config(config)\n",
"\n",
"search_result = google_search.invoke(input=\"IBM\")\n",
"output = json.loads(search_result.get(\"output\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is supposed to be maximum 3 results."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"print(len(output))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Invoke the tool with an input schema\n",
"\n",
"We need to get another tool (with an input schema) for the example purpose."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"weather_tool = watsonx_toolkit.get_tool(\"Weather\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To check if a tool has an input schema and view its properties, you can look at the tool's `tool_input_schema`.\n",
"\n",
"In this example, the tool has an input schema that contains one required and one optional parameter."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'type': 'object',\n",
" 'properties': {'location': {'title': 'location',\n",
" 'description': 'Name of the location',\n",
" 'type': 'string'},\n",
" 'country': {'title': 'country',\n",
" 'description': 'Name of the state or country',\n",
" 'type': 'string'}},\n",
" 'required': ['location']}"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"weather_tool.tool_input_schema"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To correctly pass an input to `invoke()`, you need to create an `invoke_input` dictionary with required parameter as a key with its value."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'output': 'Current weather in New York:\\nTemperature: 12.1°C\\nRain: 0mm\\nRelative humidity: 36%\\nWind: 8.1km/h\\n'}"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"invoke_input = {\n",
" \"location\": \"New York\",\n",
"}\n",
"\n",
"weather_result = weather_tool.invoke(input=invoke_input)\n",
"weather_result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This time the output is a single string value. To fetch and print it you can execute the below cell."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current weather in New York:\n",
"Temperature: 12.1°C\n",
"Rain: 0mm\n",
"Relative humidity: 36%\n",
"Wind: 8.1km/h\n",
"\n"
]
}
],
"source": [
"output = weather_result.get(\"output\")\n",
"print(output)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Invoke the tool with a ToolCall\n",
"\n",
"We can also invoke the tool with a ToolCall, in which case a ToolMessage will be returned:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"ToolMessage(content='{\"output\": \"Current weather in Los Angeles:\\\\nTemperature: 13.3°C\\\\nRain: 0mm\\\\nRelative humidity: 89%\\\\nWind: 3.3km/h\\\\n\"}', name='Weather', tool_call_id='1')"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"invoke_input = {\n",
" \"location\": \"Los Angeles\",\n",
"}\n",
"tool_call = dict(\n",
" args=invoke_input,\n",
" id=\"1\",\n",
" name=weather_tool.name,\n",
" type=\"tool_call\",\n",
")\n",
"weather_tool.invoke(input=tool_call)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use within an agent"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"from langchain_ibm import ChatWatsonx\n",
"\n",
"llm = ChatWatsonx(\n",
" model_id=\"meta-llama/llama-3-3-70b-instruct\",\n",
" url=\"https://us-south.ml.cloud.ibm.com\",\n",
" project_id=\"PASTE YOUR PROJECT_ID HERE\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.prebuilt import create_react_agent\n",
"\n",
"tools = [weather_tool]\n",
"agent = create_react_agent(llm, tools)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"What is the weather in Boston?\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" Weather (chatcmpl-tool-fe07ca2f5b5a4fd584eaedc889bea5b7)\n",
" Call ID: chatcmpl-tool-fe07ca2f5b5a4fd584eaedc889bea5b7\n",
" Args:\n",
" location: Boston\n",
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
"Name: Weather\n",
"\n",
"{\"output\": \"Current weather in Boston:\\nTemperature: 9.1°C\\nRain: 0mm\\nRelative humidity: 41%\\nWind: 24.5km/h\\n\"}\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"The current weather in Boston is:\n",
"Temperature: 9.1°C\n",
"Rain: 0mm\n",
"Relative humidity: 41%\n",
"Wind: 24.5km/h\n"
]
}
],
"source": [
"example_query = \"What is the weather in Boston?\"\n",
"\n",
"events = agent.stream(\n",
" {\"messages\": [(\"user\", example_query)]},\n",
" stream_mode=\"values\",\n",
")\n",
"for event in events:\n",
" event[\"messages\"][-1].pretty_print()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## API reference\n",
"\n",
"For detailed documentation of all `WatsonxToolkit` features and configurations head to the [API reference](https://python.langchain.com/api_reference/ibm/toolkit/langchain_ibm.toolkit.WatsonxToolkit.html)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "langchain-ibm",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}