mirror of
https://github.com/ollama/ollama-python.git
synced 2026-07-21 09:05:23 -04:00
Add way to abort a streaming response from chat / generate #110
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @paulrobello on GitHub (Jul 15, 2024).
I don't see any way to abort a streaming response from chat / generate methods
Is this or will this be supported?
Given the following snippet how can you properly abort the stream? Simply breaking from the for chunk loop is not enough.
@antoninoLorenzo commented on GitHub (Jul 26, 2024):
Technically there is no way of doing it, as you can see in that issue on
llama.cpprepository; the "brute-force" way is to add aKeyboardInterruptduring the stream, for example:However that approach may cause problems, the main one is that probably the Ollama server will continue sending stuff, however given that the stream is closed it will send chunks to nothing. To better understand what could happen you should have either
httpxknowledge (what_client.pyuses to make requests) or Go knowledge (whatOllamais built in).@mxyng commented on GitHub (Jul 30, 2024):
exiting the generator is sufficient to abort the request and stop generation, e.g.
@WabaScript2 commented on GitHub (Apr 4, 2025):
Hi Mxyng, does this solution actually terminate the response generation as you would expect when using the API directly and hitting CTRL + C?
If not, we break the stream, but the model is still using resources on the machine until its response is complete. I'm not sure about the python sdk, but the JS one does offer a proper abort method: https://github.com/ollama/ollama-js/blob/main/examples/abort/abort-single-request.ts
@whs commented on GitHub (Jun 22, 2025):
Checking in Wireshark, it seems that Ollama Python doesn't actually stop the stream after the iterator is aborted.
It seems that Python intentionally do not stop the stream when you break out of it - you can still start another loop to continue reading from the stream.
@whs commented on GitHub (Jun 22, 2025):
I think I've found a workaround.
Simply throw an exception where you'd use
break, then outside theasync foryou catch it:I can see that RST packets do get sent this way, and the server response with context canceled.
@ryamldess commented on GitHub (Oct 8, 2025):
I tried the StopIteration example above; does not work. Creating a task does not work. Break does not work. I need a way to kill a chat when context panics occur.