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

# IBM watsonx.ai 集成

> 使用 LangChain Python 集成 IBM watsonx.ai 工具。

> `WatsonxToolkit` 是 IBM [watsonx.ai](https://www.ibm.com/products/watsonx-ai) 工具包的封装。

本示例展示了如何使用 `watsonx.ai` 工具包通过 `LangChain`。

## 概述

### 集成细节

| 类 | 包 | 可序列化 | [JS 支持](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/tools/ibm.md) | 下载次数 | 版本 |
| :- | :- | :-: | :-: | :-: | :-: |
| [`WatsonxToolkit`](https://reference.langchain.com/python/langchain-ibm/WatsonxToolkit) | [`langchain-ibm`](https://reference.langchain.com/python/langchain-ibm) | ❌ | ✅ | ![PyPI - 下载](https://img.shields.io/pypi/dm/langchain-ibm?style=flat-square\&label=%20) | ![PyPI - 版本](https://img.shields.io/pypi/v/langchain-ibm?style=flat-square\&label=%20) |

## 设置

要访问 IBM watsonx.ai 工具包，您需要创建一个 IBM watsonx.ai 账户，获取一个 API 密钥，并安装 `langchain-ibm` 集成包。

### 凭证

此单元格定义了与 watsonx 工具包协同工作所需的 WML 凭证。

**操作：** 提供 IBM Cloud 用户 API 密钥。详细信息，请参阅
[文档](https://cloud.ibm.com/docs/account?topic=account-userapikey\&interface=ui)。

```python theme={null}
import os
from getpass import getpass

watsonx_api_key = getpass()
os.environ["WATSONX_APIKEY"] = watsonx_api_key
```

此外，您还可以将其他密钥作为环境变量传递。

```python theme={null}
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 集成包位于 `langchain-ibm` 包中：

```python theme={null}
!pip install -qU langchain-ibm
```

## 实例化

初始化 `WatsonxToolkit` 类。

```python theme={null}
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 软件设置](https://ibm.github.io/watsonx-ai-python-sdk/setup_cpd.html)。

对于某些需求，可以将 IBM 的 [`APIClient`](https://ibm.github.io/watsonx-ai-python-sdk/base.html#apiclient) 对象传递给 `WatsonxToolkit` 类。

```python theme={null}
from ibm_watsonx_ai import APIClient

api_client = APIClient(...)

watsonx_toolkit = WatsonxToolkit(
    watsonx_client=api_client,
)
```

## 工具

### 获取所有工具

可以将所有可用工具作为 `WatsonxTool` 对象的列表获取。

```python theme={null}
watsonx_toolkit.get_tools()
```

> [!NOTE]
>
> 可用工具的列表可能因 IBM watsonx.ai for IBM Cloud 或 IBM watsonx.ai 软件而异。

```text theme={null}
[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>)]
```

### 获取单个工具

您也可以按名称获取特定的 `WatsonxTool`。

```python theme={null}
google_search = watsonx_toolkit.get_tool(tool_name="GoogleSearch")
```

## 调用

### 使用简单输入调用工具

```python theme={null}
search_result = google_search.invoke({"q": "IBM"})
search_result
```

```json theme={null}
{'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/"}]'}
```

要获取接收到的结果列表，可以执行下方单元格。

```python theme={null}
import json

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

### 使用配置调用工具

要检查工具是否具有配置模式并查看其属性，可以查看工具的 `tool_config_schema`。

在此示例中，该工具具有包含 `maxResults` 参数的配置模式，用于设置返回的最大结果数量。

```python theme={null}
google_search.tool_config_schema
```

```text theme={null}
{'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` 参数，需要使用 `set_tool_config()` 方法，并根据上方 `tool_config_schema` 传递正确的 `dict`。

```python theme={null}
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 个结果。

```python theme={null}
print(len(output))
```

```text theme={null}
3
```

### 使用输入模式调用工具

为了示例目的，我们需要获取另一个具有输入模式的工具。

```python theme={null}
weather_tool = watsonx_toolkit.get_tool("Weather")
```

要检查工具是否具有输入模式并查看其属性，可以查看工具的 `tool_input_schema`。

在此示例中，该工具具有包含一个必需参数和一个可选参数的输入模式。

```python theme={null}
weather_tool.tool_input_schema
```

```text theme={null}
{'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()`，需要创建一个 `invoke_input` 字典，其中必需参数作为键，并为其赋值。

```python theme={null}
invoke_input = {
    "location": "New York",
}

weather_result = weather_tool.invoke(input=invoke_input)
weather_result
```

```python theme={null}
{'output': 'Current weather in New York:\nTemperature: 0°C\nRain: 0mm\nRelative humidity: 63%\nWind: 7.6km/h\n'}
```

这次输出是一个单个字符串值。要获取并打印它，可以执行下方单元格。

```python theme={null}
output = weather_result.get("output")
print(output)
```

```text theme={null}
Current weather in New York:
Temperature: 0°C
Rain: 0mm
Relative humidity: 63%
Wind: 7.6km/h
```

### 使用 ToolCall 调用工具

我们也可以使用 ToolCall 调用工具，此时将返回一个 ToolMessage：

```python theme={null}
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)
```

```text theme={null}
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')
```

## 在智能体中使用

```python theme={null}
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",
)
```

```python theme={null}
from langchain.agents import create_agent


tools = [weather_tool]
agent = create_agent(llm, tools)
```

```python theme={null}
example_query = "What is the weather in Boston?"

stream = agent.stream_events(
    {"messages": [("user", example_query)]},
    version="v3",
)
for snapshot in stream.values:
    snapshot["messages"][-1].pretty_print()
```

```text theme={null}
================================ 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 参考

有关所有 `WatsonxToolkit` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/python/langchain-ibm/WatsonxToolkit)。

***

> 官方原文：[src/oss/python/integrations/tools/ibm\_watsonx.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/tools/ibm_watsonx.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.