Python 與 JavaScript 函式庫
2024 年 1 月 23 日
Ollama Python 和 JavaScript 函式庫的初始版本現已推出
這兩個函式庫都能讓您以幾行程式碼,將新的和現有的應用程式與 Ollama 整合,並分享 Ollama REST API 的功能和體驗。
開始使用
Python
pip install ollama
import ollama
response = ollama.chat(model='llama2', messages=[
{
'role': 'user',
'content': 'Why is the sky blue?',
},
])
print(response['message']['content'])
JavaScript
npm install ollama
import ollama from 'ollama'
const response = await ollama.chat({
model: 'llama2',
messages: [{ role: 'user', content: 'Why is the sky blue?' }],
})
console.log(response.message.content)
使用案例
這兩個函式庫都支援 Ollama 的完整功能集。以下是一些 Python 的範例
串流
for chunk in chat('mistral', messages=messages, stream=True):
print(chunk['message']['content'], end='', flush=True)
多模態
with open('image.png', 'rb') as file:
response = ollama.chat(
model='llava',
messages=[
{
'role': 'user',
'content': 'What is strange about this image?',
'images': [file.read()],
},
],
)
print(response['message']['content'])
文字完成
result = ollama.generate(
model='stable-code',
prompt='// A c function to reverse a string\n',
)
print(result['response'])
建立自訂模型
modelfile='''
FROM llama2
SYSTEM You are mario from super mario bros.
'''
ollama.create(model='example', modelfile=modelfile)
自訂用戶端
ollama = Client(host='my.ollama.host')
更多範例可在 Python 和 JavaScript 函式庫的 GitHub 儲存庫中找到。
新的 GitHub 帳號
這些函式庫和主要的 Ollama 儲存庫現在都位於新的 GitHub 組織中:ollama!感謝所有維護函式庫以透過 Dart、Swift、C#、Java、PHP、Rust 等與 Ollama 互動的出色社群成員 – 完整清單在此處提供 here – 請隨時發送 Pull Request 以新增您建立或喜歡使用的函式庫。
特別感謝 ollama-js
的原始作者 Saul,以及所有其他致力於社群函式庫以使 Ollama 更容易從不同程式語言存取的人。