Skip to content
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
38 changes: 36 additions & 2 deletions terminal/serve/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3382,6 +3382,36 @@ def _held_tail(text: str, tags) -> int:
return 0


def _in_json_string(text: str) -> bool:
"""Whether JSON text that `text` starts ends inside a string."""
in_str = esc = False
for c in text:
if esc:
esc = False
elif in_str and c == "\\":
esc = True
elif c == '"':
in_str = not in_str
return in_str


def _ink_call_end(s: str, final: bool) -> tuple[int, int] | None:
"""Where a call block's body `s` ends, as (index, length of the tag there): the first <|end_message|> or next
message start outside the JSON's strings; None if there is none yet."""
ends = sorted([(i, len(INK_END)) for i in _find_all(s, INK_END)] + [(i, 0) for i in _find_all(s, INK_MSG)])
for i, n in ends:
if not _in_json_string(s[:i]):
return i, n
return ends[0] if ends and final else None


def _find_all(s: str, tag: str):
i = s.find(tag)
while i >= 0:
yield i
i = s.find(tag, i + 1)


class InklingOutputParser(OutputParser):
"""The parser for Inkling 2's replies (Thinking Machines; the tokenizer's pre-tokenizer `inkling2`). A reply is a
list of blocks, each a message of the model's that ends with <|end_message|>:
Expand All @@ -3390,8 +3420,8 @@ class InklingOutputParser(OutputParser):
<|message_model|><|content_text|>...<|end_message|>
<|message_model|>NAME<|content_invoke_tool_json|>{"name":"NAME","args":{...}}<|end_message|>

The tags are control tokens, so a block's text cannot hold one: nothing here has to tell a quoted tag from a real
one. A call is a call for a tool the request declared (OutputParser's rule); any other is returned as the text
The tags are control tokens, but the model can write their text with ordinary tokens, and the parser reads text: a
call's JSON may hold one in a string (_ink_call_end). A call is a call for a tool the request declared (OutputParser's rule); any other is returned as the text
it was written as. Text outside every block is content."""

def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False,
Expand Down Expand Up @@ -3478,6 +3508,10 @@ def _read(self, final: bool) -> list[Event]:
ends = [(i, len(t)) for i, t in ((s.find(INK_END), INK_END), (s.find(INK_MSG), "")) if i >= 0]
end = min(ends) if ends else None
if self.mode == "call":
# a call's JSON can hold the tags' text in a string ("print('<|end_message|>')"): its end is the
# first tag outside the JSON's strings. Where every tag is inside one, the JSON has not closed:
# wait for the rest, and at the end of the reply take the first tag (the call is the text it is)
end = _ink_call_end(s, final)
if end is None and not final:
return out
body = s if end is None else s[:end[0]]
Expand Down
16 changes: 16 additions & 0 deletions terminal/serve/test_inkling.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,22 @@ def test_a_call_that_is_not_json_is_text(self):
evs = read(broken, 10_000, tools=SCHEMA)
self.assertEqual(said(evs, "content"), broken[:-len(END)])

def test_the_block_end_in_a_string_argument_does_not_end_the_call(self):
# llama.cpp 29b52d398b reads this as the call; the tags' text can be in a string the model writes as text
tools = [{"name": "python", "parameters": {"properties": {"code": {"type": "string"}}}}]
call = '<|message_model|>python<|content_invoke_tool_json|>{"name":"python","args":{"code":"print(\'<|end_message|>\')"}}'
for step in (1, 4, 10_000):
with self.subTest(step=step):
evs = read(call + END + TEXT + STOP, step, tools=tools)
self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"],
[{"code": "print('<|end_message|>')"}])
self.assertEqual(said(evs, "content"), "Rome")
# JSON that never closes: at the end, the block ends at its first tag and is the text it was written as
broken = '<|message_model|>python<|content_invoke_tool_json|>{"name":"python","args":{"code":"x' + END
evs = read(broken + TEXT, 3, tools=tools)
self.assertFalse([e for e in evs if e.kind == "tool_call"])
self.assertEqual(said(evs, "content"), broken[:-len(END)] + "Rome")

def test_a_reply_whose_text_block_the_prompt_opened(self):
evs = read("Rome" + END + STOP, 3, opened=True)
self.assertEqual((said(evs, "reasoning"), said(evs, "content")), ("", "Rome"))
Expand Down
Loading