Ollama Python 库
Ollama Python 库提供了将 Python 3.8+ 项目与 Ollama 集成的最简单方法。
先决条件
- 应该安装并运行 Ollama
- 拉取一个模型以与库一起使用:例如
ollama pull <model>
ollama pull llama3.2
- 有关可用模型的更多信息,请参阅 Ollama.com。
安装
pip install ollama
用法
from ollama import chat
from ollama import ChatResponse
response: ChatResponse = chat(model='llama3.2', messages=[
{
'role': 'user',
'content': 'Why is the sky blue?',
},
])
print(response['message']['content'])
# or access fields directly from the response object
print(response.message.content)
有关响应类型的更多信息,请参阅 _types.py。
流式处理响应
可以通过设置 来启用响应流。stream=True
from ollama import chat
stream = chat(
model='llama3.2',
messages=[{
'role': 'user', 'content': 'Why is the sky blue?'}],
stream=True,
)
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)
自定义客户端
可以通过实例化 或从 创建自定义客户端。Client
AsyncClient
ollama
所有额外的关键字参数都传递到 httpx 中。客户端。
from ollama import Client
client = Client(
host='http://localhost:11434',
headers={
'x-some-header': 'some-value'}
)
response = client.chat(model='llama3.2', messages=[
{
'role': 'user',
'content': 'Why is the sky blue?',
},
])
异步客户端
该类用于发出异步请求。它可以配置与类相同的字段。AsyncClient
Client
import asyncio
from ollama import AsyncClient
async def chat():
message = {
'role': 'user', 'content': 'Why is the sky blue?'}
response = await AsyncClient().chat(model='llama3.2', messages=[message])
asyncio.run(chat())
设置 modify 函数以返回 Python 异步生成器:stream=True
import asyncio
from ollama import AsyncClient
async def chat():
message = {
'role': 'user', 'content': 'Why is the sky blue?'}
async for part in await AsyncClient().chat(model='llama3.2', messages=[message], stream=True):
print(part['message']['content'], end='', flush=True)
asyncio.run(chat())
应用程序接口
Ollama Python 库的 API 是围绕 Ollama REST API 设计的
聊天
ollama.chat(model='llama3.2', messages=[{
'role': 'user', 'content': 'Why is the sky blue?'}])
生成
ollama.generate(model='llama3.2', prompt='Why is the sky blue?')
列表
ollama.list()
显示
ollama.show('llama3.2')
创造
ollama.create(model='example', from_='llama3.2', system="You are Mario from Super Mario Bros.")
复制
ollama.copy('llama3.2', 'user/llama3.2')
删除
ollama.delete('llama3.2')
拉
ollama.pull('llama3.2')
推
ollama.push('user/llama3.2')
嵌入
ollama.embed(model='llama3.2', input='The sky is blue because of rayleigh scattering')
嵌入(批处理)
ollama.embed(model='llama3.2', input=['The sky is blue because of rayleigh scattering', 'Grass is green because of chlorophyll'])
附言
ollama.ps()
错误
如果请求返回错误状态或在流式传输时检测到错误,则会引发错误。
model = 'does-not-yet-exist'
try:
ollama.chat(model)
except ollama.ResponseError as e:
print('Error:', e.error)
if e.status_code == 404:
ollama.pull(model)