一行代码初始化多种模型:创新性使用Langchain的init_chat_model

311 阅读2分钟
# 一行代码初始化多种模型:创新性使用Langchain的init_chat_model

## 引言

在构建基于大型语言模型(LLM)的应用程序时,允许终端用户选择不同的模型提供者和模型是常见需求。这通常需要编写逻辑以根据用户配置初始化不同的模型。`init_chat_model()` 方法则使得这一过程变得简单,它支持多种模型集成,无需操心导入路径和类名。

## 主要内容

### 支持的模型

要支持的模型,请确保已安装相关的集成包。例如,要初始化 OpenAI 模型,您应该安装 `langchain-openai````bash
%pip install -qU langchain>=0.2.8 langchain-openai langchain-anthropic langchain-google-vertexai

确保 langchain-core 版本 >= 0.2.8,以使用此功能。

基本用法

使用 init_chat_model 方法可以方便地初始化不同的模型实例:

from langchain.chat_models import init_chat_model

# 使用API代理服务提高访问稳定性
gpt_4o = init_chat_model("gpt-4o", model_provider="openai", temperature=0)
claude_opus = init_chat_model("claude-3-opus-20240229", model_provider="anthropic", temperature=0)
gemini_15 = init_chat_model("gemini-1.5-pro", model_provider="google_vertexai", temperature=0)

print("GPT-4o: " + gpt_4o.invoke("what's your name").content + "\n")
print("Claude Opus: " + claude_opus.invoke("what's your name").content + "\n")
print("Gemini 1.5: " + gemini_15.invoke("what's your name").content + "\n")

模型提供者推断

init_chat_model() 可以根据常见的模型名称自动推断模型提供者。例如,任何以 gpt-3gpt-4 开头的模型都将被推断为 openai

gpt_4o = init_chat_model("gpt-4o", temperature=0)

创建可配置模型

可以通过指定 configurable_fields 创建一个运行时可配置的模型:

configurable_model = init_chat_model(temperature=0)

configurable_model.invoke("what's your name", config={"configurable": {"model": "gpt-4o"}})

代码示例

以下是一个完整的代码示例,展示如何通过 API 初始化多个模型:

from langchain.chat_models import init_chat_model

# 使用API代理服务提高访问稳定性
gpt_4o = init_chat_model("gpt-4o", temperature=0)
gemini_15 = init_chat_model("gemini-1.5-pro", temperature=0)

response1 = gpt_4o.invoke("what's the weather in New York?")
response2 = gemini_15.invoke("how's the traffic in San Francisco?")

print("GPT-4o: " + response1.content)
print("Gemini 1.5: " + response2.content)

常见问题和解决方案

  • 无法访问API:在某些地区,由于网络限制,可能需要使用 API 代理服务以提高访问稳定性。
  • 版本不兼容:确保 langchain 和相关集成包版本符合要求。

总结和进一步学习资源

使用 init_chat_model() 可以大大简化模型集成过程,同时提高代码的灵活性。更多信息和高级用法可以参考Langchain的官方文档。

参考资料

  1. Langchain官方文档
  2. PyPI上的Langchain库

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

---END---