116 lines
5.5 KiB
Python
116 lines
5.5 KiB
Python
#!/usr/bin/env python3
|
|
"""CPU HTTP custom-tool contract smoke; uses a synthetic byte-token engine."""
|
|
import http.client
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
|
|
|
|
def main():
|
|
binary = Path(sys.argv[1]).resolve()
|
|
spec = importlib.util.spec_from_file_location('cancel_fixture', Path(__file__).with_name('smoke-worker-cancel.py'))
|
|
fixture = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(fixture)
|
|
with tempfile.TemporaryDirectory(prefix='strata-custom-http-') as directory:
|
|
root = Path(directory)
|
|
fixture.tokenizer(root)
|
|
source = '\n print("Привіт 🌍")\n'
|
|
markup = '<tool_call>\n<function=run>\n<parameter=input>\n' + source + '\n</parameter>\n</function>\n</tool_call>'
|
|
for name, output in [('plain', markup), ('reason', 'Think.</think>\n\n' + markup), ('answer', 'OK')]:
|
|
data = output.encode()
|
|
(root / name).write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n')
|
|
engine = root / 'engine.sh'
|
|
engine.write_text('''#!/bin/sh
|
|
printf 'READY 262144 stop\\n'
|
|
count=0
|
|
while IFS= read -r line; do
|
|
case "$line" in
|
|
'GEN '*)
|
|
count=$((count + 1))
|
|
case "$count" in
|
|
1|2) cat "$2/plain" ;;
|
|
3|4) cat "$2/reason" ;;
|
|
5) cat "$2/answer" ;;
|
|
*) printf 'ERR unexpected generation\\n' ;;
|
|
esac ;;
|
|
QUIT) exit 0 ;;
|
|
esac
|
|
done
|
|
''')
|
|
engine.chmod(0o700)
|
|
with socket.socket() as probe:
|
|
probe.bind(('127.0.0.1', 0))
|
|
port = probe.getsockname()[1]
|
|
env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}',
|
|
'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]),
|
|
'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'}
|
|
|
|
def request(path, body=None):
|
|
conn = http.client.HTTPConnection('127.0.0.1', port, timeout=8)
|
|
conn.request('POST' if body is not None else 'GET', path,
|
|
json.dumps(body) if body is not None else None,
|
|
{'Content-Type': 'application/json'})
|
|
response = conn.getresponse()
|
|
status, data = response.status, response.read().decode()
|
|
conn.close()
|
|
return status, data
|
|
|
|
with tempfile.TemporaryFile() as logs:
|
|
process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True)
|
|
try:
|
|
deadline = time.monotonic() + 8
|
|
while True:
|
|
try:
|
|
if request('/ready')[0] == 200:
|
|
break
|
|
except OSError:
|
|
pass
|
|
assert process.poll() is None and time.monotonic() < deadline
|
|
time.sleep(0.02)
|
|
for effort in ['none', 'low']:
|
|
for stream in [False, True]:
|
|
payload = {'model': 'fixture', 'input': 'Run source', 'max_output_tokens': 1024,
|
|
'reasoning': {'effort': effort}, 'stream': stream,
|
|
'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]}
|
|
code, data = request('/v1/responses', payload)
|
|
assert code == 200, (code, data)
|
|
if stream:
|
|
events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')]
|
|
assert [e['sequence_number'] for e in events] == list(range(len(events)))
|
|
assert events[-1]['type'] == 'response.completed'
|
|
assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source
|
|
assert next(e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done') == source
|
|
assert not any('function_call_arguments' in e['type'] for e in events)
|
|
result = events[-1]['response']
|
|
else:
|
|
result = json.loads(data)
|
|
call = result['output'][-1]
|
|
assert call['type'] == 'custom_tool_call' and call['input'] == source
|
|
assert call['name'] == 'run' and 'arguments' not in call
|
|
code, data = request('/v1/responses', {'model': 'fixture', 'reasoning': {'effort': 'none'},
|
|
'previous_response_id': result['id'], 'input': [
|
|
{'type': 'custom_tool_call_output', 'call_id': call['call_id'], 'output': 'done'}]})
|
|
assert code == 200 and json.loads(data)['output'][0]['content'][0]['text'] == 'OK'
|
|
payload['tools'][0]['format'] = {'type': 'grammar', 'syntax': 'lark', 'definition': 'start: WORD'}
|
|
assert request('/v1/responses', payload)[0] == 400
|
|
assert json.loads(request('/metrics')[1])['generation']['started'] == 5
|
|
finally:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=8)
|
|
except subprocess.TimeoutExpired:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
process.wait()
|
|
print('Custom text tools passed: JSON/SSE, reasoning, exact input, continuation, grammar rejection; CPU fixtures only')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|