# 一行代码搞定!如何快速初始化多种语言模型
## 引言
在开发语言模型应用时,许多场景需要允许终端用户指定希望应用所使用的模型提供商和模型版本。为了应对这种需求,我们需要编写逻辑来根据用户配置初始化不同的聊天模型。然而,通过使用 `init_chat_model()` 方法,我们可以轻松地初始化多个模型集成,而无需担心导入路径和类名。
## 主要内容
### 支持的模型
`init_chat_model()` 支持多种模型集成,可参考其 API 文档获取完整支持的模型列表。需要注意的是,为了支持某些模型提供商,你需要提前安装相应的集成包。例如,要初始化 OpenAI 模型,你需要安装 `langchain-openai`。
### 基本使用
以下示例展示了如何使用 `init_chat_model()` 方法初始化不同的聊天模型:
```python
from langchain.chat_models import init_chat_model
# 返回一个 langchain_openai.ChatOpenAI 实例
gpt_4o = init_chat_model("gpt-4o", model_provider="openai", temperature=0) # 使用API代理服务提高访问稳定性
# 返回一个 langchain_anthropic.ChatAnthropic 实例
claude_opus = init_chat_model("claude-3-opus-20240229", model_provider="anthropic", temperature=0) # 使用API代理服务提高访问稳定性
# 返回一个 langchain_google_vertexai.ChatVertexAI 实例
gemini_15 = init_chat_model("gemini-1.5-pro", model_provider="google_vertexai", temperature=0) # 使用API代理服务提高访问稳定性
# 使用这些模型
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-3...
或 gpt-4...
开头的模型都会被视作使用 OpenAI 提供的模型。
创建可配置的模型
可以通过 configurable_fields
参数创建一个运行时可配置的模型。以下示例展示了如何在调用时动态指定模型:
configurable_model = init_chat_model(temperature=0)
# 指定使用哪种模型
configurable_model.invoke(
"what's your name", config={"configurable": {"model": "gpt-4o"}} # 使用API代理服务提高访问稳定性
)
代码示例
# 一个完整的例子,演示如何使用可配置模型进行多种操作
from langchain_core.pydantic_v1 import BaseModel, Field
class GetWeather(BaseModel):
"""获取特定位置的当前天气"""
location: str = Field(..., description="城市和州,例如 San Francisco, CA")
class GetPopulation(BaseModel):
"""获取特定位置的人口信息"""
location: str = Field(..., description="城市和州,例如 San Francisco, CA")
# 初始化模型
llm = init_chat_model(temperature=0)
# 绑定工具
llm_with_tools = llm.bind_tools([GetWeather, GetPopulation])
# 调用
response = llm_with_tools.invoke(
"what's bigger in 2024 LA or NYC", config={"configurable": {"model": "gpt-4o"}} # 使用API代理服务提高访问稳定性
).tool_calls
print(response)
常见问题和解决方案
-
网络限制:在某些地区,由于网络限制,访问模型提供商的API可能不稳定。建议使用API代理服务来提高访问稳定性。
-
版本兼容性:确保你的
langchain
版本是0.2.8
或更高,以避免不兼容问题。
总结与进一步学习资源
通过 init_chat_model()
方法,我们可以轻松地初始化多种语言模型,为开发应用提供了极大的便利。如果想深入了解更多内容,可以参考以下资源:
参考资料
- Langchain 官方文档
- OpenAI API 文档
- Pydantic 官方文档
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---