This is code generates and prints an ollama response. While it is printing I would like to listen whether the shortcuts ctrl-s or ctrl-l was pressed. Is this possible? If possible I would like this to be done with prompt_toolkit, since this is already a dependency.
code
import ollama
response = ollama.chat(
messages=[{'role':'user','content':'hey'}],
model = 'hf.co/bartowski/Mistral-Large-Instruct-2411-GGUF:IQ2_M',
keep_alive=-1,
stream=True,
)
for comp in response:
delta = comp['message']['content']
print(delta, end='',flush=True)
Other requiremenets:
It should not consume other keyboard shortcuts, so e.g. ctrl-c should still be able to abort generation.
I also don't want the terminal text input to be messed up if the program exits unexpectantly
The code should be as short as possible
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here’s a minimal example showing how to stream your Ollama response while listening for ⌃S and ⌃L using only prompt_toolkit. It won’t steal other keys (e.g. ⌃C still sends SIGINT), and it will restore your terminal state even on a crash:
python
import asyncio
import ollama
from prompt_toolkit import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.patch_stdout import patch_stdout
# 1) Define the two key‐bindings we care about
kb = KeyBindings()
@kb.add("c-s")
def _(event):
# do whatever you want on Ctrl-S
print("\n[Ctrl-S pressed]")
@kb.add("c-l")
def _(event):
# do whatever you want on Ctrl-L
print("\n[Ctrl-L pressed]")
# 2) Create a prompt_toolkit Application with our key bindings
app = Application(
key_bindings=kb,
full_screen=False, # we don't need a full-screen UI
)
async def printer():
# 3) Fire off the streaming request
response = ollama.chat(
messages=[{"role": "user", "content": "hey"}],
model="hf.co/bartowski/Mistral-Large-Instruct-2411-GGUF:IQ2_M",
keep_alive=-1,
stream=True,
)
# 4) Print as we get deltas
for comp in response:
print(comp["message"]["content"], end="", flush=True)
# 5) Once done, tell the app to exit its event loop
app.exit()
async def main():
# patch_stdout lets us safely print() while the app is running
async with patch_stdout():
# Schedule our printer() coroutine
task = asyncio.create_task(printer())
# Run the prompt_toolkit event loop until app.exit() is called
await app.run_async()
# Wait for printer() to finish (in case of errors)
await task
if __name__ == "__main__":
# This will also respect Ctrl-C / SIGINT
asyncio.run(main())
Explanation:
We create a KeyBindings object and bind only c-s and c-l.
We build a bare‐bones Application (no prompt shown, no full‐screen) so it can listen to keys.
In printer() we stream the Ollama response and print() each chunk.
When streaming is done, we call app.exit() to break out of run_async().
We wrap everything in patch_stdout() so that print() calls don’t garble the prompt_toolkit renderer.
asyncio.run(main()) still lets Ctrl-C kill the program and leaves your terminal sane even if something blows up.
That’s all — under 40 lines, no extra dependencies, no hijacking of other shortcuts, and safe terminal cleanup.