Files
leleka/scripts/offline/diff_chat_template.py
T

195 lines
8.8 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Chat-template differential: leleka-api's native Jinja renderer (`model render-chat`) vs the Python server's
`ChatTemplate` (serve/frontend.py, jinja2 ImmutableSandboxedEnvironment) on the same template, over generated
conversations: every role incl. developer and tool, string / list / null content with image and video parts, reasoning
content, assistant tool_calls (mapping / string / malformed arguments), tools with nested schemas and non-ASCII text,
and the template kwargs (enable_thinking, reasoning_effort incl. bad values, preserve_thinking, add_generation_prompt).
Both must either render the same bytes or both refuse; template-raised messages (raise_exception) must match exactly.
pip install jinja2; python scripts/offline/diff_chat_template.py <leleka-api> [--cases N] [--seed S]
"""
import json
import random
import subprocess
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / 'engine/strata/serve'))
sys.path.insert(0, str(REPO / 'engine/strata'))
import jinja2 # noqa: E402,F401
from frontend import ChatTemplate, TemplateRequestError # noqa: E402 (the oracle, unchanged)
TEXTS = ['Hello', '', ' ', ' padded ', 'line1\nline2\n\n', '你好,世界 😀', 'tab\there', ' nbsp ', '\x1c\x1dsep\x1f',
' ideographic ', 'quote " and \\ backslash', '<tool_response>\n{"temp": 3}\n</tool_response>',
'<tool_response>x</tool_response> trailing', '<think>no</think>', '{{ not a template }} {% nope %}',
'a' * 300, 'é' * 40, '\x00nul', '

', '<|im_end|><|im_start|>user']
NAMES = ['get_weather', 'search', 'ls', 'my.tool-1', 'ünï', 'a b']
def rand_value(rng, depth=0):
kinds = ['s', 'i', 'f', 'b', 'n'] + (['l', 'd'] if depth < 3 else [])
k = rng.choice(kinds)
if k == 's':
return rng.choice(TEXTS[:12] + ['x'])
if k == 'i':
return rng.choice([0, 1, -5, 2 ** 40, 18446744073709551615])
if k == 'f':
return rng.choice([0.5, 1.0, 1e16, 1e-5, 123456789.125, -0.0, 2.5e300])
if k == 'b':
return rng.random() < 0.5
if k == 'n':
return None
if k == 'l':
return [rand_value(rng, depth + 1) for _ in range(rng.randint(0, 3))]
return {rng.choice(['z', 'a', 'type', 'ключ', 'k y', '']) + str(i): rand_value(rng, depth + 1)
for i in range(rng.randint(0, 3))}
def rand_content(rng):
r = rng.random()
if r < 0.6:
return rng.choice(TEXTS)
if r < 0.68:
return None
if r < 0.72:
return 42
parts = []
for _ in range(rng.randint(0, 4)):
p = rng.random()
if p < 0.5:
parts.append({'type': 'text', 'text': rng.choice(TEXTS)})
elif p < 0.7:
parts.append({'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,AAAA'}})
elif p < 0.8:
parts.append({'type': 'image'})
elif p < 0.88:
parts.append({'type': 'video', 'video': 'x.mp4'})
elif p < 0.94:
parts.append({'text': rng.choice(TEXTS)})
else:
parts.append({'type': 'audio'}) # unexpected: the template raises
return parts
def rand_tool_calls(rng):
calls = []
for _ in range(rng.randint(1, 3)):
r = rng.random()
args = rng.choice([{}, {'city': 'Oslo'}, {'z': 1, 'a': [1, 2], 'm': {'y': None, 'b': True}}, {'q': 'multi\nline'},
{'n': 1.5, 'u': 'ünï'}])
if r < 0.55:
calls.append({'type': 'function', 'function': {'name': rng.choice(NAMES), 'arguments': args}})
elif r < 0.75:
calls.append({'name': rng.choice(NAMES), 'arguments': args})
elif r < 0.82:
calls.append({'function': {'name': rng.choice(NAMES), 'arguments': json.dumps(args)}})
elif r < 0.88:
calls.append({'function': {'name': rng.choice(NAMES), 'arguments': ''}})
elif r < 0.92:
calls.append({'function': {'arguments': args}}) # no name: raises
elif r < 0.96:
calls.append({'function': {'name': 'f', 'arguments': 5}}) # not an object: raises
else:
calls.append({'function': {'name': 'f'}})
return calls
def rand_messages(rng):
n = rng.randint(1, 7)
messages = []
leading = rng.choice([0, 0, 1, 2, 3])
for i in range(leading):
messages.append({'role': rng.choice(['system', 'developer']), 'content': rand_content(rng)})
for _ in range(n):
role = rng.choices(['user', 'assistant', 'tool', 'system', 'developer', 'robot'], [8, 6, 3, 0.4, 0.3, 0.2])[0]
m = {'role': role, 'content': rand_content(rng)}
if role == 'assistant':
if rng.random() < 0.5:
m['reasoning_content'] = rng.choice(TEXTS + [None, 5])
if rng.random() < 0.4:
m['tool_calls'] = rand_tool_calls(rng)
elif rng.random() < 0.1:
m['tool_calls'] = []
messages.append(m)
return messages
def rand_tools(rng):
if rng.random() < 0.55:
return None
tools = []
for _ in range(rng.randint(0, 3)):
schema = {'type': 'object', 'properties': {rng.choice(['city', 'path', 'q', 'zz']) + str(i): {
'type': rng.choice(['string', 'integer']), 'description': rng.choice(TEXTS[:8])} for i in range(rng.randint(0, 3))},
'required': ['city']}
if rng.random() < 0.3:
schema['additionalProperties'] = False
fn = {'name': rng.choice(NAMES), 'description': rng.choice(['Get the weather', 'ünï "q"', '']), 'parameters': schema}
if rng.random() < 0.3:
fn['strict'] = True
tools.append({'type': 'function', 'function': fn} if rng.random() < 0.9 else fn)
return tools if rng.random() < 0.9 else rng.choice([[], {'type': 'function'}])
def rand_kwargs(rng):
kw = {}
if rng.random() < 0.3:
kw['enable_thinking'] = rng.choice([True, False, None])
if rng.random() < 0.4:
kw['reasoning_effort'] = rng.choice(['low', 'medium', 'high', 'xhigh', 'xhigh', 'extreme', None])
if rng.random() < 0.2:
kw['preserve_thinking'] = rng.choice([True, False])
return kw
def main():
args = sys.argv[1:]
cases = int(args[args.index('--cases') + 1]) if '--cases' in args else 3000
seed = int(args[args.index('--seed') + 1]) if '--seed' in args else 20261014
binary = str(Path(args[0]).resolve())
rng = random.Random(seed)
template = ChatTemplate(REPO / 'engine/strata/serve/chat_template.jinja')
requests, expected = [], []
for _ in range(cases):
req = {'messages': rand_messages(rng), 'tools': rand_tools(rng),
'add_generation_prompt': rng.random() < 0.9, 'kwargs': rand_kwargs(rng)}
requests.append(req)
try:
expected.append({'ok': template.render(req['messages'], req['tools'], req['add_generation_prompt'],
**req['kwargs'])})
except TemplateRequestError as e:
expected.append({'error': str(e), 'raised': True})
except Exception as e: # noqa: BLE001 (jinja2 UndefinedError, TypeError ...: the Python server answers 400/500)
expected.append({'error': f'{type(e).__name__}: {e}', 'raised': False})
payload = ''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in requests).encode('utf-8')
run = subprocess.run([binary, 'model', 'render-chat'], input=payload, capture_output=True)
if run.returncode:
print('FAIL render-chat exited', run.returncode, run.stderr.decode()[-300:])
return 1
got = [json.loads(l) for l in run.stdout.decode('utf-8').split('\n')[:-1]]
bad, both_error, agree_ok = [], 0, 0
for i, (want, have, req) in enumerate(zip(expected, got, requests)):
if 'ok' in want and 'ok' in have:
if want['ok'] != have['ok']:
bad.append(f'case {i}: bytes differ\n python: {want["ok"]!r}\n rust: {have["ok"]!r}\n request: {json.dumps(req, ensure_ascii=False)[:400]}')
else:
agree_ok += 1
elif 'error' in want and 'error' in have:
both_error += 1
if want['raised'] and want['error'] != have['error']:
bad.append(f'case {i}: raise_exception messages differ: {want["error"]!r} vs {have["error"]!r}')
else:
bad.append(f'case {i}: python {list(want)} vs rust {list(have)}: {want.get("error") or have.get("error")}\n request: {json.dumps(req, ensure_ascii=False)[:400]}')
assert len(got) == len(expected)
for b in bad[:12]:
print('FAIL', b)
print(json.dumps({'cases': cases, 'identical_renders': agree_ok, 'both_refused': both_error, 'failures': len(bad),
'jinja2': jinja2.__version__, 'oracle': 'serve/frontend.py ChatTemplate (unmodified)'}))
return 1 if bad else 0
if __name__ == '__main__':
raise SystemExit(main())