IBM watsonx.ai
WatsonxToolkit 是一个用于包裹 IBM watsonx.ai 工具包的封装。
这只是一个例子,说明了如何使用watsonx.ai工具包以及LangChain的用法。
概览
集成细节
| Class | 包 | 序列化 | JS支持 | Package downloads | Package 最新版本 |
|---|---|---|---|---|---|
| WatsonxToolkit | langchain-ibm | ❌ | ✅ |
设置
要访问IBM Watsonx.ai工具包,您需要创建一个IBM Watsonx.ai账号、获取API密钥,并安装langchain-ibm集成包。
Credentials
这个单元格定义了与watsonx工具包工作所需的WML凭据。
操作: 提供IBM Cloud用户API密钥。详情请参见 文档。
import os
from getpass import getpass
watsonx_api_key = getpass()
os.environ["WATSONX_APIKEY"] = watsonx_api_key
您还可以通过环境变量传递额外的密钥。
import os
os.environ["WATSONX_URL"] = "your service instance url"
os.environ["WATSONX_TOKEN"] = "your token for accessing the service instance"
安装
The LangChain IBM集成位于langchain-ibm包中:
!pip install -qU langchain-ibm
Instantiation
初始化 WatsonxToolkit 类。
from langchain_ibm import WatsonxToolkit
watsonx_toolkit = WatsonxToolkit(
url="https://us-south.ml.cloud.ibm.com",
)
对于某些需求,可以选择将IBM的APIClient对象传递给WatsonxToolkit类。
from ibm_watsonx_ai import APIClient
api_client = APIClient(...)
watsonx_toolkit = WatsonxToolkit(
watsonx_client=api_client,
)
工具
获取所有工具
可以将所有可用工具以WatsonxTool对象列表的形式获取。
watsonx_toolkit.get_tools()
[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。
google_search = watsonx_toolkit.get_tool(tool_name="GoogleSearch")
Invocation
使用简单输入调用工具
search_result = google_search.invoke(input="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/"}]'}
要获取收到的结果列表,请执行以下单元格。
import json
output = json.loads(search_result.get("output"))
output
使用配置调用工具
要检查一个工具是否有配置方案以及查看其属性,您可以查看工具的tool_config_schema。
在这个示例中,该工具的配置方案包含一个参数maxResults来设置要返回的最大结果数。
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参数,您需要使用set_tool_config()方法并根据上述tool_config_schema传递正确的dict。
import json
config = {"maxResults": 3}
google_search.set_tool_config(config)
search_result = google_search.invoke(input="IBM")
output = json.loads(search_result.get("output"))
存在最多只能有3个结果。
print(len(output))
3
使用输入模式调用工具
我们需要为示例目的获取另一个工具(带有输入方案)。
weather_tool = watsonx_toolkit.get_tool("Weather")
要检查一个工具是否有输入模式并查看其属性,您可以查看工具的tool_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(),您需要创建一个包含所需参数作为键及其值的invoke_input字典。
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 = weather_result.get("output")
print(output)
Current weather in New York:
Temperature: 0°C
Rain: 0mm
Relative humidity: 63%
Wind: 7.6km/h
使用ToolCall调用工具
我们也可以通过 ToolCall 调用工具,这时会返回一个 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')
使用于代理
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 langgraph.prebuilt import create_react_agent
tools = [weather_tool]
agent = create_react_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()
================================[1m Human Message [0m=================================
What is the weather in Boston?
==================================[1m Ai Message [0m==================================
Tool Calls:
Weather (chatcmpl-tool-6a6c21402c824e43bdd2e8ba390af4a8)
Call ID: chatcmpl-tool-6a6c21402c824e43bdd2e8ba390af4a8
Args:
location: Boston
=================================[1m Tool Message [0m=================================
Name: Weather
{"output": "Current weather in Boston:\nTemperature: -1°C\nRain: 0mm\nRelative humidity: 53%\nWind: 8.3km/h\n"}
==================================[1m Ai Message [0m==================================
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参考。