跳转到主要内容

Home Assistant的Ollama官方Python客户端的分支。

项目描述

注意:这是一个官方Ollama Python库的分支,通过放宽依赖关系,以便与Home Assistant兼容。

Ollama Python库

Ollama Python库为将Python 3.8+项目与Ollama集成提供了最简单的方法。

安装

pip install ollama

用法

import ollama
response = ollama.chat(model='llama2', messages=[
  {
    'role': 'user',
    'content': 'Why is the sky blue?',
  },
])
print(response['message']['content'])

流式响应

可以通过设置stream=True,修改函数调用以返回一个Python生成器,其中每个部分都是流中的对象,来启用响应流。

import ollama

stream = ollama.chat(
    model='llama2',
    messages=[{'role': 'user', 'content': 'Why is the sky blue?'}],
    stream=True,
)

for chunk in stream:
  print(chunk['message']['content'], end='', flush=True)

API

Ollama Python库的API设计基于Ollama REST API

聊天

ollama.chat(model='llama2', messages=[{'role': 'user', 'content': 'Why is the sky blue?'}])

生成

ollama.generate(model='llama2', prompt='Why is the sky blue?')

列表

ollama.list()

显示

ollama.show('llama2')

创建

modelfile='''
FROM llama2
SYSTEM You are mario from super mario bros.
'''

ollama.create(model='example', modelfile=modelfile)

复制

ollama.copy('llama2', 'user/llama2')

删除

ollama.delete('llama2')

拉取

ollama.pull('llama2')

推送

ollama.push('user/llama2')

嵌入

ollama.embeddings(model='llama2', prompt='They sky is blue because of rayleigh scattering')

自定义客户端

可以通过以下字段创建自定义客户端

  • host:要连接到的Ollama主机
  • timeout:请求的超时时间
from ollama import Client
client = Client(host='http://localhost:11434')
response = client.chat(model='llama2', messages=[
  {
    'role': 'user',
    'content': 'Why is the sky blue?',
  },
])

异步客户端

import asyncio
from ollama import AsyncClient

async def chat():
  message = {'role': 'user', 'content': 'Why is the sky blue?'}
  response = await AsyncClient().chat(model='llama2', messages=[message])

asyncio.run(chat())

设置 stream=True 会修改函数以返回一个 Python 异步生成器

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='llama2', messages=[message], stream=True):
    print(part['message']['content'], end='', flush=True)

asyncio.run(chat())

错误

如果请求返回错误状态或检测到流中存在错误,将引发错误。

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)

项目详情


下载文件

下载您平台对应的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

ollama_hass-0.1.7.tar.gz (9.7 kB 查看哈希值)

上传时间

构建分布

ollama_hass-0.1.7-py3-none-any.whl (9.5 kB 查看哈希值)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面