Skip to content
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

Add cancel() method to interrupt a stream #733

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ def __init__(
self.scores: npt.NDArray[np.single] = np.ndarray(
(n_ctx, self._n_vocab), dtype=np.single
)
self.cancel_stream = False

@property
def _input_ids(self) -> npt.NDArray[np.intc]:
Expand Down Expand Up @@ -975,6 +976,11 @@ def _create_completion(
finish_reason = "stop"
break

if self.cancel_stream:
finish_reason = "cancel"
self.cancel_stream = False
break

completion_tokens.append(token)

all_text = self.detokenize(completion_tokens)
Expand Down Expand Up @@ -1702,6 +1708,11 @@ def load_state(self, state: LlamaState) -> None:
if llama_cpp.llama_set_state_data(self.ctx, llama_state) != state_size:
raise RuntimeError("Failed to set llama state data")

def cancel(self) -> None:
"""Cancel a streaming completion."""
if self.n_tokens > 0:
self.cancel_stream = True

def n_ctx(self) -> int:
"""Return the context window size."""
assert self.ctx is not None
Expand Down