Skip to content

Add stream_options support according to OpenAI API #1552

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 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
220 changes: 142 additions & 78 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -1116,6 +1116,56 @@ def decode_batch(seq_sizes: List[int]):
else:
return output

def _create_chunk(
self,
completion_id: str,
created: int,
model_name: str,
text: str,
logprobs_or_none: Union[Optional[CompletionLogprobs], None],
include_usage: bool,
index: int,
finish_reason: Union[str, None],
usage: Union[Dict[str, Any], None] = None,
) -> CreateChatCompletionStreamResponse:
"""
Create chunks for streaming API, depending on whether usage is requested or
not they need (or don't need) an additional field
"""

if include_usage:
token = {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": text,
"index": index,
"logprobs": logprobs_or_none,
"finish_reason": finish_reason,
},
],
"usage": usage,
}
else:
token = {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": text,
"index": index,
"logprobs": logprobs_or_none,
"finish_reason": finish_reason,
}
],
}
return token

def _create_completion(
self,
prompt: Union[str, List[int]],
Expand All @@ -1133,6 +1183,7 @@ def _create_completion(
repeat_penalty: float = 1.0,
top_k: int = 40,
stream: bool = False,
stream_options: Optional[StreamOptions] = None,
seed: Optional[int] = None,
tfs_z: float = 1.0,
mirostat_mode: int = 0,
Expand Down Expand Up @@ -1363,6 +1414,11 @@ def logit_bias_processor(
break

if stream:
if stream_options and "include_usage" in stream_options:
include_usage = stream_options["include_usage"]
else:
include_usage = False

remaining_tokens = completion_tokens[returned_tokens:]
remaining_text = self.detokenize(
remaining_tokens,
Expand Down Expand Up @@ -1442,24 +1498,23 @@ def logit_bias_processor(
"top_logprobs": [top_logprob],
}
returned_tokens += 1
yield {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": self.detokenize(
[token],
prev_tokens=prompt_tokens
+ completion_tokens[:returned_tokens],
).decode("utf-8", errors="ignore"),
"index": 0,
"logprobs": logprobs_or_none,
"finish_reason": None,
}
],
}
text = (
self.detokenize(
[token],
prev_tokens=prompt_tokens
+ completion_tokens[:returned_tokens],
).decode("utf-8", errors="ignore"),
)
yield self._create_chunk(
completion_id=completion_id,
created=created,
model_name=model_name,
text=text,
finish_reason=None,
index=0,
logprobs_or_none=logprobs_or_none,
include_usage=include_usage,
)
else:
while len(remaining_tokens) > 0:
decode_success = False
Expand Down Expand Up @@ -1488,20 +1543,16 @@ def logit_bias_processor(
remaining_tokens = remaining_tokens[i:]
returned_tokens += i

yield {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": ts,
"index": 0,
"logprobs": None,
"finish_reason": None,
}
],
}
yield self._create_chunk(
index=0,
finish_reason=None,
completion_id=completion_id,
created=created,
model_name=model_name,
text=ts,
logprobs_or_none=None,
include_usage=include_usage,
)

if len(completion_tokens) >= max_tokens:
text = self.detokenize(completion_tokens, prev_tokens=prompt_tokens)
Expand Down Expand Up @@ -1580,54 +1631,60 @@ def logit_bias_processor(
if token_end_position == end - 1:
break
returned_tokens += 1
yield {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": last_text[
: len(last_text) - (token_end_position - end)
].decode("utf-8", errors="ignore"),
"index": 0,
"logprobs": logprobs_or_none,
"finish_reason": None,
}
],
}
text = last_text[
: len(last_text) - (token_end_position - end)
].decode("utf-8", errors="ignore")

yield self._create_chunk(
completion_id=completion_id,
created=created,
model_name=model_name,
text=text,
logprobs_or_none=logprobs_or_none,
include_usage=include_usage,
index=0,
finish_reason=None,
)
break
returned_tokens += 1
yield {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": self.detokenize([token]).decode(
"utf-8", errors="ignore"
),
"index": 0,
"logprobs": logprobs_or_none,
"finish_reason": None,
}
],
}
yield {
"id": completion_id,
"object": "text_completion",
"created": created,
"model": model_name,
"choices": [
{
"text": "",
"index": 0,
"logprobs": None,
"finish_reason": finish_reason,
}
],
}
text = self.detokenize([token]).decode("utf-8", errors="ignore")
yield self._create_chunk(
completion_id=completion_id,
created=created,
model_name=model_name,
text=text,
logprobs_or_none=logprobs_or_none,
include_usage=include_usage,
index=0,
finish_reason=None,
)
yield self._create_chunk(
completion_id= completion_id,
created= created,
model_name=model_name,
text="",
index=0,
logprobs_or_none= None,
include_usage=include_usage,
usage=None,
finish_reason=finish_reason)

if include_usage:
yield self._create_chunk(
completion_id=completion_id,
created=created,
model_name=model_name,
text="",
logprobs_or_none=None,
include_usage=include_usage,
index=0,
finish_reason=None,
usage={
"prompt_tokens": len(prompt_tokens),
"completion_tokens": returned_tokens,
"total_tokens": len(prompt_tokens) + returned_tokens,
},
)
if self.cache:
if self.verbose:
print("Llama._create_completion: cache save", file=sys.stderr)
Expand Down Expand Up @@ -1736,6 +1793,7 @@ def logit_bias_processor(
},
}


def create_completion(
self,
prompt: Union[str, List[int]],
Expand All @@ -1753,6 +1811,7 @@ def create_completion(
repeat_penalty: float = 1.0,
top_k: int = 40,
stream: bool = False,
stream_options: Optional[StreamOptions] = None,
seed: Optional[int] = None,
tfs_z: float = 1.0,
mirostat_mode: int = 0,
Expand Down Expand Up @@ -1816,6 +1875,7 @@ def create_completion(
repeat_penalty=repeat_penalty,
top_k=top_k,
stream=stream,
stream_options=stream_options,
seed=seed,
tfs_z=tfs_z,
mirostat_mode=mirostat_mode,
Expand Down Expand Up @@ -1850,6 +1910,7 @@ def __call__(
repeat_penalty: float = 1.0,
top_k: int = 40,
stream: bool = False,
stream_options: Optional[StreamOptions] = None,
seed: Optional[int] = None,
tfs_z: float = 1.0,
mirostat_mode: int = 0,
Expand Down Expand Up @@ -1913,6 +1974,7 @@ def __call__(
repeat_penalty=repeat_penalty,
top_k=top_k,
stream=stream,
stream_options=stream_options,
seed=seed,
tfs_z=tfs_z,
mirostat_mode=mirostat_mode,
Expand All @@ -1938,6 +2000,7 @@ def create_chat_completion(
min_p: float = 0.05,
typical_p: float = 1.0,
stream: bool = False,
stream_options: Optional[StreamOptions] = False,
stop: Optional[Union[str, List[str]]] = [],
seed: Optional[int] = None,
response_format: Optional[ChatCompletionRequestResponseFormat] = None,
Expand Down Expand Up @@ -2011,6 +2074,7 @@ def create_chat_completion(
logprobs=logprobs,
top_logprobs=top_logprobs,
stream=stream,
stream_options=stream_options,
stop=stop,
seed=seed,
response_format=response_format,
Expand Down
Loading