Node.js使用ollama模块遇TypeError: ollama.chat is not a function问题求助
TypeError: ollama.chat is not a function 问题排查与解决
问题原因
你使用的ollama@0.5.0版本采用ES模块(ESM)作为默认模块规范,而当前用CommonJS的require方式导入时,无法直接获取到chat方法——因为ESM的默认导出在CommonJS环境中需要通过.default属性访问,直接require('ollama')得到的是一个包含默认导出的对象,而非直接的ollama实例。
解决方案1:调整CommonJS导入方式
修改导入代码,显式访问默认导出:
const ollama = require('ollama').default; async function chatWithLlama() { try { const response = await ollama.chat({ model: 'llama3', messages: [{ role: 'user', content: 'Why is the sky blue?' }], }); console.log(response.message.content); } catch (error) { console.error('Error:', error); } } chatWithLlama();
解决方案2:切换为ES模块写法
- 在
package.json中添加"type": "module",将项目设为ESM环境:
{ "name": "nodejs", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@api/pplx": "file:.api/apis/pplx", "@types/node": "^18.0.6", "ollama": "^0.5.0" } }
- 修改代码为ESM导入语法:
import ollama from 'ollama'; async function chatWithLlama() { try { const response = await ollama.chat({ model: 'llama3', messages: [{ role: 'user', content: 'Why is the sky blue?' }], }); console.log(response.message.content); } catch (error) { console.error('Error:', error); } } chatWithLlama();
解决方案3:降级ollama版本
若不想调整模块规范,可以降级到对CommonJS支持更直接的ollama@0.4.0版本:
npm uninstall ollama npm install ollama@0.4.0
降级后无需修改原有导入代码,即可正常调用ollama.chat()。
验证步骤
- 确认Mac上的Ollama服务处于运行状态
- 确保
llama3模型已通过ollama pull llama3安装完成 - 运行修改后的脚本,检查是否能正常输出响应内容
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

