test_stream_tool_calls.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. """python -m unittest discover -s tests -p test_stream_tool_calls.py -v"""
  2. import json
  3. import unittest
  4. from pathlib import Path
  5. from unittest.mock import patch
  6. import torch
  7. from fastapi.testclient import TestClient
  8. from openai import OpenAI
  9. from transformers import AutoTokenizer
  10. from model.model_minimind import MiniMindConfig, MiniMindForCausalLM
  11. from scripts import serve_openai_api as server
  12. TOOL = '<tool_call>{"name":"weather","arguments":{"city":"杭州"}}</tool_call>'
  13. TOOLS = [{'type': 'function', 'function': {'name': 'weather', 'parameters': {
  14. 'type': 'object', 'properties': {'city': {'type': 'string'}}, 'required': ['city']}}}]
  15. class ScriptedModel:
  16. def __init__(self, chunks, tokenize=False):
  17. self.chunks, self.tokenize = chunks, tokenize
  18. def generate(self, input_ids, streamer, **kwargs):
  19. if self.tokenize:
  20. streamer.put(input_ids.cpu())
  21. for token in streamer.tokenizer.encode(''.join(self.chunks), add_special_tokens=False):
  22. streamer.put(torch.tensor([token]))
  23. streamer.end()
  24. else:
  25. for chunk in self.chunks:
  26. streamer.on_finalized_text(chunk)
  27. streamer.on_finalized_text('', stream_end=True)
  28. class StreamToolTests(unittest.TestCase):
  29. @classmethod
  30. def setUpClass(cls):
  31. cls.tokenizer = AutoTokenizer.from_pretrained(
  32. Path(__file__).resolve().parents[1] / 'model', local_files_only=True)
  33. def setUp(self):
  34. globals_patch = patch.multiple(server, tokenizer=self.tokenizer, device='cpu',
  35. model=ScriptedModel([]), create=True)
  36. globals_patch.start()
  37. self.addCleanup(globals_patch.stop)
  38. self.http = TestClient(server.app)
  39. self.addCleanup(self.http.close)
  40. self.request = {'model': 'minimind', 'messages': [{'role': 'user', 'content': 'Hi'}]}
  41. def frames(self, chunks, thinking=False):
  42. server.model = ScriptedModel(chunks)
  43. response = self.http.post('/v1/chat/completions', json={
  44. **self.request, 'stream': True, 'open_thinking': thinking})
  45. self.assertEqual(response.status_code, 200)
  46. self.assertIn('text/event-stream', response.headers['content-type'])
  47. return [json.loads(line[6:]) for line in response.text.splitlines()
  48. if line.startswith('data: ')]
  49. def assert_output(self, frames, content, count, reasoning=''):
  50. self.assertFalse(any('error' in frame for frame in frames), frames)
  51. deltas = [frame['choices'][0]['delta'] for frame in frames]
  52. self.assertEqual(''.join(d.get('content', '') for d in deltas), content)
  53. self.assertEqual(''.join(d.get('reasoning_content', '') for d in deltas), reasoning)
  54. calls = [call for d in deltas for call in d.get('tool_calls', [])]
  55. self.assertEqual(len(calls), count)
  56. self.assertEqual([call['index'] for call in calls], list(range(count)))
  57. self.assertEqual(len({call['id'] for call in calls}), count)
  58. for call in calls:
  59. self.assertEqual(call['function']['name'], 'weather')
  60. self.assertEqual(json.loads(call['function']['arguments']), {'city': '杭州'})
  61. self.assertEqual(frames[-1]['choices'][0]['finish_reason'], 'tool_calls' if count else 'stop')
  62. def test_split_markers_and_multiple_calls(self):
  63. text = 'Before ' + TOOL + ' between ' + TOOL + ' after'
  64. for chunks in ([text], list(text), ['Before <tool_', text[len('Before <tool_'):]]):
  65. with self.subTest(chunks=len(chunks)):
  66. self.assert_output(self.frames(chunks), 'Before between after', 2)
  67. def test_thinking_boundary_and_tool_text_inside_reasoning(self):
  68. reasoning = 'Consider ' + TOOL + '\n'
  69. text = reasoning + '</think>\n\n' + TOOL + ' answer'
  70. self.assert_output(self.frames(list(text), thinking=True), ' answer', 1, reasoning)
  71. def test_invalid_and_unfinished_calls_preserve_text(self):
  72. for text in ('plain < text', 'end <tool_', '<tool_call>{"name":',
  73. '<tool_call>bad json</tool_call>', '<tool_call>[]</tool_call>'):
  74. with self.subTest(text=text):
  75. self.assert_output(self.frames(list(text)), text, 0)
  76. invalid = '<tool_call>bad json</tool_call>'
  77. self.assert_output(self.frames([invalid, TOOL]), invalid, 1)
  78. def test_empty_and_unfinished_thinking(self):
  79. self.assert_output(self.frames([]), '', 0)
  80. self.assert_output(self.frames(['reason </thi'], thinking=True), '', 0, 'reason </thi')
  81. def test_plain_content_and_tool_call_arrive_before_generation_ends(self):
  82. def generate(input_ids, streamer, **kwargs):
  83. streamer.on_finalized_text('first ')
  84. self.assertTrue(continue_generation.wait(5))
  85. streamer.on_finalized_text(TOOL)
  86. self.assertTrue(finish_generation.wait(5))
  87. streamer.on_finalized_text(' last', stream_end=True)
  88. from threading import Event
  89. continue_generation, finish_generation = Event(), Event()
  90. server.model.generate = generate
  91. stream = server.generate_stream_response(self.request['messages'], 0.7, 0.92, 128)
  92. self.addCleanup(continue_generation.set)
  93. self.addCleanup(finish_generation.set)
  94. first = json.loads(next(stream))
  95. if first['choices'][0]['delta'].get('role') == 'assistant':
  96. first = json.loads(next(stream))
  97. self.assertEqual(first['choices'][0]['delta']['content'], 'first ')
  98. continue_generation.set()
  99. call = json.loads(next(stream))
  100. self.assertEqual(call['choices'][0]['delta']['tool_calls'][0]['function']['name'], 'weather')
  101. finish_generation.set()
  102. self.assert_output([first, call] + [json.loads(frame) for frame in stream], 'first last', 1)
  103. def test_real_text_streamer_and_openai_client(self):
  104. server.model = ScriptedModel(['Before ', TOOL, ' after'], tokenize=True)
  105. with OpenAI(api_key='local-test', base_url='http://testserver/v1',
  106. http_client=self.http, max_retries=0) as client:
  107. chunks = list(client.chat.completions.create(**self.request, tools=TOOLS, stream=True))
  108. self.assertEqual(''.join(c.choices[0].delta.content or '' for c in chunks), 'Before after')
  109. calls = [call for c in chunks for call in c.choices[0].delta.tool_calls or []]
  110. self.assertEqual(len(calls), 1)
  111. self.assertEqual(calls[0].index, 0)
  112. self.assertEqual(json.loads(calls[0].function.arguments), {'city': '杭州'})
  113. def test_tiny_minimind_generation(self):
  114. torch.manual_seed(42)
  115. server.model = MiniMindForCausalLM(MiniMindConfig(
  116. hidden_size=32, num_hidden_layers=1, num_attention_heads=4,
  117. num_key_value_heads=2, intermediate_size=64,
  118. vocab_size=len(self.tokenizer), max_position_embeddings=256)).eval()
  119. response = self.http.post('/v1/chat/completions', json={
  120. **self.request, 'stream': True, 'max_tokens': 4})
  121. frames = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')]
  122. self.assertFalse(any('error' in frame for frame in frames), frames)
  123. self.assertEqual(frames[-1]['choices'][0]['finish_reason'], 'stop')
  124. if __name__ == '__main__':
  125. unittest.main()