llama-index llms ollama integration
Actively maintained. Last release 2 weeks ago. A safe choice.
pip install llama-index-llms-ollamaREADME as published on PyPI with version 0.12.0.
LlamaIndex Llms Integration: Ollama
Installation
To install the required package, run:
pip install llama-index-llms-ollama
Setup
- Follow the Ollama README to set up and run a local Ollama instance.
- When the Ollama app is running on your local machine, it will serve all of your local models on
localhost:11434. - Select your model when creating the
Ollamainstance by specifyingmodel=":". - You can increase the default timeout (30 seconds) by setting
Ollama(..., request_timeout=300.0). - If you set
llm = Ollama(..., model="<model family>")without a version, it will automatically look for the latest version.
Usage
Initialize Ollama
from llama_index.llms.ollama import Ollama
llm = Ollama(model="llama3.1:latest", request_timeout=120.0)
Generate Completions
To generate a text completion for a prompt, use the complete method:
resp = llm.complete("Who is Paul Graham?")
print(resp)
Chat Responses
To send a chat message and receive a response, create a list of ChatMessage instances and use the chat method:
from llama_index.core.llms import ChatMessage
messages = [
ChatMessage(
role="system", content="You are a pirate with a colorful personality."
),
ChatMessage(role="user", content="What is your name?"),
]
resp = llm.chat(messages)
print(resp)
Streaming Responses
Stream Complete
To stream responses for a prompt, use the stream_complete method:
response = llm.stream_complete("Who is Paul Graham?")
for r in response:
print(r.delta, end="")
Stream Chat
To stream chat responses, use the stream_chat method:
messages = [
ChatMessage(
role="system", content="You are a pirate with a colorful personality."
),
ChatMessage(role="user", content="What is your name?"),
]
resp = llm.stream_chat(messages)
for r in resp:
print(r.delta, end="")