JavaScript SDK 安装与配置

Ollama 官方提供了 JavaScript/TypeScript SDK,支持 Node.js 和浏览器环境。

安装 SDK

使用 npm 安装:

npm install ollama

使用 yarn 安装:

yarn add ollama

使用 pnpm 安装:

pnpm add ollama

基本使用

Node.js 环境

import ollama from 'ollama'

const response = await ollama.chat({
  model: 'llama3.2',
  messages: [{ role: 'user', content: '你好' }]
})

console.log(response.message.content)

浏览器环境

<script type="module">
import ollama from 'https://cdn.jsdelivr.net/npm/ollama/dist/browser.mjs'

const response = await ollama.chat({
  model: 'llama3.2',
  messages: [{ role: 'user', content: '你好' }]
})

console.log(response.message.content)
</script>

配置连接

自定义地址

import ollama from 'ollama'

const client = new ollama.Ollama({ host: 'http://192.168.1.100:11434' })

const response = await client.chat({
  model: 'llama3.2',
  messages: [{ role: 'user', content: '你好' }]
})

环境变量

export OLLAMA_HOST=http://192.168.1.100:11434

SDK 会自动读取环境变量。

自定义 fetch

import ollama from 'ollama'

const client = new ollama.Ollama({
  host: 'http://localhost:11434',
  fetch: customFetch
})

验证安装

import ollama from 'ollama'

try {
  const models = await ollama.list()
  console.log('连接成功!')
  console.log('已安装模型:', models.models.map(m => m.name))
} catch (error) {
  console.error('连接失败:', error.message)
}

CommonJS 支持

如果使用 CommonJS:

const ollama = require('ollama').default

async function main() {
  const response = await ollama.chat({
    model: 'llama3.2',
    messages: [{ role: 'user', content: '你好' }]
  })
  console.log(response.message.content)
}

main()

依赖说明

SDK 依赖:

  • whatwg-fetch - fetch polyfill(Node.js 环境)
  • 无其他外部依赖