Skip to content

Add CLI example for streaming Ollama responses live_ollama_cli.py #551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions examples/live_ollama_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python3

import sys
import requests
import json


def call_ollama(prompt, model="tinyllama", base_url="http://localhost:11434", stream=True):
"""
Sends a prompt to the Ollama API and streams the response back.
"""
payload = {
"model": model,
"prompt": prompt,
"stream": stream
}

try:
response = requests.post(f"{base_url}/api/generate", json=payload, stream=stream)
response.raise_for_status()

if stream:
for line in response.iter_lines():
if line:
data = json.loads(line.decode('utf-8'))
yield data.get("response", "")
else:
yield response.json().get("response", "No response received")

except requests.RequestException as e:
yield f"\n[Error] Could not connect to Ollama. Is it running?\nDetails: {str(e)}\n"


def main():
"""
Main entry point for CLI usage.
"""
# Get prompt from command-line or input
if len(sys.argv) > 1:
prompt = ' '.join(sys.argv[1:])
else:
prompt = input("Enter your prompt: ")

print("Thinking...\nOllama: ", end="", flush=True)

# Call Ollama and print the output in real-time
for chunk in call_ollama(prompt):
print(chunk, end="", flush=True)

print() # Final newline


if __name__ == "__main__":
main()