一、调用通义千问大模型
方式1:使用 @langchain/community 专属适配器
依赖安装
pnpm add @langchain/community
调用代码
import { ChatAlibabaTongyi } from "@langchain/community/chat_models/alibaba_tongyi";
const model = new ChatAlibabaTongyi({
model: "qwen-plus",
alibabaApiKey: "[你的阿里百炼API Key]",
});
async function callTongyiModel() {
const response = await model.invoke("为什么鹦鹉会说话?");
console.log(response.content);
}
callTongyiModel();
方式2:使用 @langchain/openai 兼容接口
依赖安装
pnpm add @langchain/openai
调用代码
import { ChatOpenAI } from "@langchain/openai"
const model = new ChatOpenAI({
model: "qwen-plus",
configuration: {
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
apiKey: "[你的阿里百炼API Key]",
}
});
async function callQwenByOpenAI() {
const response = await model.invoke(`1+1=?`);
console.log("单文本调用响应:", response.content);
}
callQwenByOpenAI();
二、调用 Ollama 本地模型
1. 前置条件
- 安装 Ollama:官网下载
- 拉取目标模型:
ollama pull qwen3-vl:8b
- 启动 Ollama 服务:
ollama serve(默认端口 11434)
2. 依赖安装
pnpm add @langchain/ollama
3. 核心调用代码
import { ChatOllama } from "@langchain/ollama"
const model = new ChatOllama({
model: "qwen3-vl:8b",
baseUrl: "http://localhost:11434"
});
async function callOllamaModel() {
const response = await model.invoke(`1+1=?`);
console.log("Ollama本地模型响应:", response.content);
}
callOllamaModel();
三、核心对比与选型建议
| 调用方式 | 优点 | 缺点 | 适用场景 |
|---|
| 阿里云通义千问 | 模型能力强、无需本地算力、支持多模态/复杂推理 | 需联网、消耗 API 额度、有调用频率限制 | 生产环境、复杂业务逻辑、多轮对话 |
| Ollama 本地模型 | 无网络依赖、隐私性高、免费使用、调试便捷 | 占用本地CPU/GPU、模型能力相对弱、不支持部分高级功能 | 本地开发调试、隐私敏感场景、轻量计算/问答 |