TypeError:ollama.chat 不是带有 ollama 模块的 Node.js 中的函数

问题描述 投票:0回答:1

我正在开发一个 Node.js 项目,我正在尝试使用 ollama (ollama-js) 模块。但是,当我调用异步函数

chatWithLlama()
(里面有
ollama.chat()
)时,遇到以下错误:

TypeError: ollama.chat is not a function

并且

chatWithLlama()
功能还没有完成。

以下是相关代码片段:

const ollama = require('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();

有关更多上下文,这是我的 package.json:

{
  "name": "nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "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"
  }
}

我已确保 ollama 模块已使用 npm 正确安装并包含在 package.json 文件和 node_modules 目录中。我的 Mac 上还运行着 Ollama,并且已经安装了 llama3。除了此错误之外,没有发生任何其他错误,并且脚本不会崩溃。是什么导致了这个问题以及如何解决它?

javascript node.js function typeerror ollama
1个回答
0
投票

在 ECMAScript 模块(ESM)中,这 2 基本上代表同一件事:

import ollama from 'ollama';
import { default as ollama } from 'ollama';

但是,当您在 CommonJS (CJS) 中编写相同的内容时(

require()
是仅限 CJS 的模式),它相当于 ESM 中的 namespace import

const ollama = require('ollama'); // CJS
import * as ollama from 'ollama'; // ESM

因此,为了解决此问题,您应该从名为

default
的导出中读取它。以下是 CJS 和 ESM 中默认导入之间的翻译:

import ollama from 'ollama'; // ESM
const { default: ollama } = require('ollama'); // CJS
© www.soinside.com 2019 - 2024. All rights reserved.