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

Allow server to accept openai's new structured output "json_schema" format. #1677

Open
wants to merge 2 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
13 changes: 10 additions & 3 deletions llama_cpp/llama_chat_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ def chat_completion_handler(
if result.stopping_criteria is not None:
stopping_criteria = result.stopping_criteria

if response_format is not None and response_format["type"] == "json_object":
if response_format is not None:
grammar = _grammar_for_response_format(
response_format, verbose=llama.verbose
)
Expand Down Expand Up @@ -928,6 +928,13 @@ def _grammar_for_response_format(
response_format: llama_types.ChatCompletionRequestResponseFormat,
verbose: bool = False,
):

# convert openai type 'json_schema' to llama_cpp type 'json_object':
if response_format['type'] == "json_schema":
response_format['type'] = "json_object"
response_format['schema'] = response_format['json_schema']['schema']
del response_format['json_schema']

if response_format["type"] != "json_object":
return None

Expand Down Expand Up @@ -2830,7 +2837,7 @@ def embed_image_bytes(image_bytes: bytes):
# Get prompt tokens to avoid a cache miss
prompt = llama.input_ids[: llama.n_tokens].tolist()

if response_format is not None and response_format["type"] == "json_object":
if response_format is not None:
grammar = _grammar_for_response_format(response_format)

# Convert legacy functions to tools
Expand Down Expand Up @@ -3442,7 +3449,7 @@ def chatml_function_calling(
add_generation_prompt=True,
)

if response_format is not None and response_format["type"] == "json_object":
if response_format is not None:
grammar = _grammar_for_response_format(response_format)

return _convert_completion_to_chat(
Expand Down
5 changes: 4 additions & 1 deletion llama_cpp/llama_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,13 @@ class ChatCompletionFunctionCallOption(TypedDict):


class ChatCompletionRequestResponseFormat(TypedDict):
type: Literal["text", "json_object"]
type: Literal["text", "json_object", "json_schema"]
schema: NotRequired[
JsonType
] # https://docs.endpoints.anyscale.com/guides/json_mode/
json_schema: NotRequired[
JsonType
]


class ChatCompletionRequestMessageContentPartText(TypedDict):
Expand Down