Ollama 使用指南:Python 与 JavaScript 集成实践
什么是 Ollama?
Ollama 是一个用于在本地运行大语言模型(LLM)的工具和框架。它简化了在本地环境中部署和使用大语言模型的过程,使得开发者可以在自己的计算机上运行强大的 AI 模型,而无需依赖云服务。
Ollama 提供了 REST API 接口,并且为 Python 和 JavaScript 开发者提供了专门的 SDK,使得集成变得非常简单。
安装 Ollama
首先需要在本地安装 Ollama,可以从 Ollama 官网 下载适用于您操作系统的安装包。
安装完成后,可以通过以下命令验证安装:
拉取模型
在使用 Ollama 之前,需要先拉取所需的模型。以 gemma3 模型为例:
您可以在 Ollama 模型库 中找到更多可用的模型。
Python 中使用 Ollama
安装 Python SDK
首先需要安装 Ollama 的 Python SDK:
基本聊天功能
以下是一个简单的聊天示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| from ollama import chat from ollama import ChatResponse
response: ChatResponse = chat(model='gemma3', messages=[ { 'role': 'user', 'content': '为什么天空是蓝色的?', }, ])
print(response['message']['content'])
print(response.message.content)
|
流式响应
对于需要实时显示响应的场景,可以启用流式响应:
1 2 3 4 5 6 7 8 9 10 11 12
| from ollama import chat
stream = chat( model='gemma3', messages=[{'role': 'user', 'content': '为什么天空是蓝色的?'}], stream=True, )
for chunk in stream: print(chunk['message']['content'], end='', flush=True)
|
异步客户端
对于异步应用,可以使用 AsyncClient:
1 2 3 4 5 6 7 8 9 10
| import asyncio from ollama import AsyncClient
async def chat(): message = {'role': 'user', 'content': '为什么天空是蓝色的?'} response = await AsyncClient().chat(model='gemma3', messages=[message]) print(response.message.content)
asyncio.run(chat())
|
流式异步响应
1 2 3 4 5 6 7 8 9 10
| import asyncio from ollama import AsyncClient
async def chat(): message = {'role': 'user', 'content': '为什么天空是蓝色的?'} async for part in await AsyncClient().chat(model='gemma3', messages=[message], stream=True): print(part['message']['content'], end='', flush=True)
asyncio.run(chat())
|
自定义客户端
可以创建自定义客户端来配置特定的选项:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from ollama import Client
client = Client( host='http://localhost:11434', headers={'x-some-header': 'some-value'} )
response = client.chat(model='gemma3', messages=[ { 'role': 'user', 'content': '为什么天空是蓝色的?', }, ])
print(response.message.content)
|
其他 API 功能
Ollama Python SDK 还提供了其他功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import ollama
models = ollama.list() print(models)
model_info = ollama.show('gemma3') print(model_info)
response = ollama.generate(model='gemma3', prompt='写一首关于春天的诗') print(response.response)
embedding = ollama.embed(model='gemma3', input='天空是蓝色的因为瑞利散射') print(embedding)
|
JavaScript 中使用 Ollama
安装 JavaScript SDK
在 Node.js 项目中安装 Ollama SDK:
基本聊天功能
1 2 3 4 5 6 7 8 9 10
| import ollama from 'ollama'
const response = await ollama.chat({ model: 'gemma3', messages: [{ role: 'user', content: '为什么天空是蓝色的?' }], })
console.log(response.message.content)
|
流式响应
1 2 3 4 5 6 7 8 9 10 11 12 13
| import ollama from 'ollama'
const message = { role: 'user', content: '为什么天空是蓝色的?' } const response = await ollama.chat({ model: 'gemma3', messages: [message], stream: true, })
for await (const part of response) { process.stdout.write(part.message.content) }
|
浏览器中使用
在浏览器环境中,需要导入浏览器模块:
1 2 3 4 5 6 7 8 9
| import ollama from 'ollama/browser'
const response = await ollama.chat({ model: 'gemma3', messages: [{ role: 'user', content: '为什么天空是蓝色的?' }], })
console.log(response.message.content)
|
自定义客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { Ollama } from 'ollama'
const ollama = new Ollama({ host: 'http://localhost:11434', headers: { 'x-some-header': 'some-value' } })
const response = await ollama.chat({ model: 'gemma3', messages: [{ role: 'user', content: '为什么天空是蓝色的?' }], })
console.log(response.message.content)
|
其他 API 功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import ollama from 'ollama'
const models = await ollama.list() console.log(models)
const modelInfo = await ollama.show('gemma3') console.log(modelInfo)
const response = await ollama.generate({ model: 'gemma3', prompt: '写一首关于春天的诗' }) console.log(response.response)
const embedding = await ollama.embed({ model: 'gemma3', input: '天空是蓝色的因为瑞利散射' }) console.log(embedding)
|
错误处理
在使用 Ollama 时,需要适当处理可能出现的错误:
Python 错误处理
1 2 3 4 5 6 7 8 9 10 11 12
| import ollama from ollama import ResponseError
model = 'does-not-yet-exist'
try: ollama.chat(model) except ResponseError as e: print('错误:', e.error) if e.status_code == 404: print('模型不存在,需要先拉取模型')
|
JavaScript 错误处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import ollama from 'ollama'
try { const response = await ollama.chat({ model: 'does-not-yet-exist', messages: [{ role: 'user', content: '为什么天空是蓝色的?' }], }) console.log(response.message.content) } catch (error) { console.error('错误:', error.message) if (error.status === 404) { console.log('模型不存在,需要先拉取模型') } }
|
实际应用示例
Python 聊天机器人
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| from ollama import chat import asyncio
class ChatBot: def __init__(self, model='gemma3'): self.model = model self.history = [] def send_message(self, message): self.history.append({'role': 'user', 'content': message}) response = chat(model=self.model, messages=self.history) assistant_message = response['message'] self.history.append(assistant_message) return assistant_message['content'] def reset(self): self.history = []
bot = ChatBot() response = bot.send_message('你好,介绍一下你自己') print(response)
|
JavaScript 聊天应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import ollama from 'ollama'
class ChatBot { constructor(model = 'gemma3') { this.model = model this.history = [] } async sendMessage(message) { this.history.push({ role: 'user', content: message }) const response = await ollama.chat({ model: this.model, messages: this.history }) const assistantMessage = response.message this.history.push(assistantMessage) return assistantMessage.content } reset() { this.history = [] } }
const bot = new ChatBot() const response = await bot.sendMessage('你好,介绍一下你自己') console.log(response)
|
总结
Ollama 为开发者提供了在本地运行大语言模型的便捷方式,并且通过 Python 和 JavaScript SDK 使得集成变得非常简单。无论是构建聊天机器人、文本生成应用还是其他 AI 驱动的功能,Ollama 都能提供强大的支持。
通过本文介绍的示例代码,您可以快速开始在您的项目中使用 Ollama,充分利用大语言模型的能力来增强您的应用程序功能。