[GH-ISSUE #2439] Feature #1423

Closed
opened 2026-04-12 11:18:09 -05:00 by GiteaMirror · 0 comments
Owner

Originally created by @MikeyBeez on GitHub (Feb 10, 2024).
Original GitHub issue: https://github.com/ollama/ollama/issues/2439

I wrote this code to chunk streaming into sentences. If you want to use it to enhance your streaming api call, please do.

import nltk
from langchain_community.llms import Ollama

ANSI escape codes for colors

NEON_GREEN = '\033[92m'
RESET_COLOR = '\033[0m'

Download NLTK's PunktSentenceTokenizer

nltk.download('punkt')

llm = Ollama(model="llama2")
query = "Explain how large language models work"

sentence_buffer = ""

for chunk in llm.stream(query):
# Directly process the chunk since it's assumed to be a string
sentence_buffer += chunk
sentences = nltk.sent_tokenize(sentence_buffer)

if len(sentences) > 1: 
    print(NEON_GREEN + sentences[0] + RESET_COLOR) 
    sentence_buffer = " ".join(sentences[1:])  

Print any remaining text at the end

if sentence_buffer:
print(NEON_GREEN + sentence_buffer + RESET_COLOR)

Originally created by @MikeyBeez on GitHub (Feb 10, 2024). Original GitHub issue: https://github.com/ollama/ollama/issues/2439 I wrote this code to chunk streaming into sentences. If you want to use it to enhance your streaming api call, please do. import nltk from langchain_community.llms import Ollama # ANSI escape codes for colors NEON_GREEN = '\033[92m' RESET_COLOR = '\033[0m' # Download NLTK's PunktSentenceTokenizer nltk.download('punkt') llm = Ollama(model="llama2") query = "Explain how large language models work" sentence_buffer = "" for chunk in llm.stream(query): # Directly process the chunk since it's assumed to be a string sentence_buffer += chunk sentences = nltk.sent_tokenize(sentence_buffer) if len(sentences) > 1: print(NEON_GREEN + sentences[0] + RESET_COLOR) sentence_buffer = " ".join(sentences[1:]) # Print any remaining text at the end if sentence_buffer: print(NEON_GREEN + sentence_buffer + RESET_COLOR)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/ollama#1423