k
This commit is contained in:
1 parent
c834ce5e39
commit
1d23e56497
3 files changed
+297
-16
No files matched your search
+114
@@ -29,6 +29,120 @@ class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||
await pilot.pause(0.02)
|
||||
self.fail('Conversation did not finish')
|
||||
|
||||
async def test_average_tps_is_weighted_by_request_duration(self):
|
||||
app = await self.make_app(lambda request: httpx.Response(500))
|
||||
try:
|
||||
app.update_statistics = lambda: None
|
||||
with patch("ai_chat.monotonic", return_value=12.0):
|
||||
app._response_started = 10.0
|
||||
app.record_usage({"completion_tokens": 20})
|
||||
app.finish_response_metrics()
|
||||
with patch("ai_chat.monotonic", return_value=20.0):
|
||||
app._response_started = 12.0
|
||||
app.record_usage({"completion_tokens": 40})
|
||||
app.finish_response_metrics()
|
||||
self.assertEqual(app._total_response_tokens, 60)
|
||||
self.assertEqual(app._total_response_seconds, 10)
|
||||
self.assertEqual(app._total_response_tokens / app._total_response_seconds, 6)
|
||||
self.assertFalse(app._average_estimated)
|
||||
finally:
|
||||
await app.client.aclose()
|
||||
|
||||
async def test_statistics_update_before_stream_finishes(self):
|
||||
app = await self.make_app(lambda request: httpx.Response(500))
|
||||
send_chunk = asyncio.Event()
|
||||
chunk_consumed = asyncio.Event()
|
||||
finish = asyncio.Event()
|
||||
async def stream(ai, history):
|
||||
await send_chunk.wait()
|
||||
yield "Immediate words"
|
||||
chunk_consumed.set()
|
||||
await finish.wait()
|
||||
app.stream_ai = stream
|
||||
async with app.run_test() as pilot:
|
||||
send_chunk.set()
|
||||
await asyncio.wait_for(chunk_consumed.wait(), 2)
|
||||
# No timer tick or completed response is needed to update counts.
|
||||
rendered = io.StringIO()
|
||||
Console(file=rendered, width=100, color_system=None).print(
|
||||
app.query_one("#conversation-stats").content)
|
||||
self.assertIn("~7", rendered.getvalue())
|
||||
self.assertRegex(rendered.getvalue(), r"~7\s+4\s+")
|
||||
self.assertTrue(app._is_running)
|
||||
finish.set()
|
||||
await self.wait_finished(app, pilot)
|
||||
|
||||
async def test_statistics_stream_usage_and_transcript(self):
|
||||
def handler(request):
|
||||
self.assertTrue(json.loads(request.content)["stream_options"]["include_usage"])
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"Hello world"}}]}\n\ndata: {"choices":[],"usage":{"prompt_tokens":20,"completion_tokens":3}}\n\ndata: [DONE]\n\n')
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test(size=(100, 30)) as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
stats = app.query_one("#conversation-stats")
|
||||
rendered = io.StringIO()
|
||||
Console(file=rendered, width=100, color_system=None).print(stats.content)
|
||||
self.assertIn("WORDS", rendered.getvalue())
|
||||
self.assertEqual(sum(len(m.content.split()) for m in app.messages), 4)
|
||||
self.assertIn("1 replies", rendered.getvalue())
|
||||
self.assertIn("20 input / 3 output", rendered.getvalue())
|
||||
self.assertEqual(app.api_input_tokens, 20)
|
||||
self.assertEqual(app.api_output_tokens, 3)
|
||||
self.assertTrue(app._last_speed_exact)
|
||||
self.assertGreater(app._last_speed, 0)
|
||||
self.assertGreater(stats.size.height, 0)
|
||||
self.assertLessEqual(stats.region.bottom, app.size.height)
|
||||
|
||||
async def test_statistics_fallback_does_not_count_partial_text(self):
|
||||
def handler(request):
|
||||
if json.loads(request.content).get("stream"):
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"discard this text"}}]}\n\ndata: {"error":"broken"}\n\n')
|
||||
return httpx.Response(200, json={"choices": [{"message": {"content": "Final answer"}}]})
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
rendered = io.StringIO()
|
||||
Console(file=rendered, width=100, color_system=None).print(app.query_one("#conversation-stats").content)
|
||||
stats = rendered.getvalue()
|
||||
self.assertEqual(sum(len(m.content.split()) for m in app.messages), 4)
|
||||
self.assertIn("API usage: not reported", stats)
|
||||
self.assertFalse(app._last_speed_exact)
|
||||
self.assertEqual(app.api_output_tokens, 0)
|
||||
|
||||
async def test_long_history_is_bounded_without_losing_transcript(self):
|
||||
app = await self.make_app(lambda request: httpx.Response(500))
|
||||
try:
|
||||
app.messages = [ChatMessage("user", "Original topic", "System")]
|
||||
app.messages.extend(ChatMessage("assistant", str(i) + "x" * 3000,
|
||||
"AI 1" if i % 2 == 0 else "AI 2")
|
||||
for i in range(60))
|
||||
history = app.history_for("AI 1")
|
||||
self.assertLessEqual(sum(len(m["content"]) + 64 for m in history), 12000)
|
||||
self.assertEqual(history[0]["content"], "Original topic")
|
||||
self.assertEqual(history[-1]["content"], app.messages[-1].content)
|
||||
self.assertEqual(len(app.messages), 61)
|
||||
finally:
|
||||
await app.client.aclose()
|
||||
|
||||
async def test_empty_response_recovers_on_retry(self):
|
||||
calls = []
|
||||
def handler(request):
|
||||
calls.append(json.loads(request.content))
|
||||
if len(calls) <= 2:
|
||||
if calls[-1].get("stream"):
|
||||
return httpx.Response(200, text="data: [DONE]\n\n")
|
||||
return httpx.Response(200, json={"choices": [{"message": {"content": ""}}]})
|
||||
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"recovered"}}]}\n\ndata: [DONE]\n\n')
|
||||
app = await self.make_app(handler)
|
||||
async with app.run_test() as pilot:
|
||||
await self.wait_finished(app, pilot)
|
||||
self.assertEqual(app.current_turn, 1)
|
||||
self.assertEqual(app.messages[-1].content, "recovered")
|
||||
self.assertEqual(len(app.query(MessageBubble)), 2)
|
||||
|
||||
def test_timeout_error_has_a_name(self):
|
||||
self.assertIn("ReadTimeout", AIChatApp.describe_error(httpx.ReadTimeout("")))
|
||||
|
||||
async def test_stream_usage_and_speaker_roles(self):
|
||||
requests = []
|
||||
def handler(request):
|
||||
|
||||
Reference in new issue
Block a user