WebLLM
兼容性
仅适用于网页环境。
您可以使用 LangChain 的 WebLLM 集成,在您的网页浏览器中直接运行大语言模型(LLM)。
安装配置
要与本地模型通信,您需要安装 WebLLM SDK 模块。
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- Yarn
- pnpm
npm install -S @mlc-ai/web-llm @langchain/community @langchain/core
yarn add @mlc-ai/web-llm @langchain/community @langchain/core
pnpm add @mlc-ai/web-llm @langchain/community @langchain/core
使用方法
请注意,当第一次调用模型时,WebLLM 会下载该模型的完整权重文件。这可能会达到数个 GB,具体取决于您的用户网络连接和计算机配置,可能并非所有用户都能完成下载。虽然浏览器会对模型进行缓存以便后续调用使用,但我们建议您尽量使用最小的模型。
另外,在调用和加载模型时,我们建议使用 单独的 Web Worker,以避免阻塞主线程的执行。
// Must be run in a web environment, e.g. a web worker
import { ChatWebLLM } from "@langchain/community/chat_models/webllm";
import { HumanMessage } from "@langchain/core/messages";
// Initialize the ChatWebLLM model with the model record and chat options.
// Note that if the appConfig field is set, the list of model records
// must include the selected model record for the engine.
// You can import a list of models available by default here:
// https://github.com/mlc-ai/web-llm/blob/main/src/config.ts
//
// Or by importing it via:
// import { prebuiltAppConfig } from "@mlc-ai/web-llm";
const model = new ChatWebLLM({
model: "Phi-3-mini-4k-instruct-q4f16_1-MLC",
chatOptions: {
temperature: 0.5,
},
});
await model.initialize((progress: Record<string, unknown>) => {
console.log(progress);
});
// Call the model with a message and await the response.
const response = await model.invoke([
new HumanMessage({ content: "What is 1 + 1?" }),
]);
console.log(response);
/*
AIMessage {
content: ' 2\n',
}
*/
API Reference:
- ChatWebLLM from
@langchain/community/chat_models/webllm - HumanMessage from
@langchain/core/messages
同时,也支持流式传输。
示例
有关完整的端到端示例,请查看 此项目。
相关内容
Related
- Chat model conceptual guide
- Chat model how-to guides