ollama python
v0.4.4
Ollama Python 库提供了将 Python 3.8+ 项目与 Ollama 集成的最简单方法。
ollama pull <model>
例如ollama pull llama3.2
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 )
可以通过实例化ollama
中的Client
或AsyncClient
来创建自定义客户端。
所有额外的关键字参数都会传递到httpx.Client
中。
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 ())
设置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 = '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' )
modelfile = '''
FROM llama3.2
SYSTEM You are mario from super mario bros.
'''
ollama . create ( model = 'example' , modelfile = modelfile )
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 )