askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_ai_streaming.py · 9.6 KB · 224 lines
| 1 | """Streamed turns: text arrives as it is written, tools still run between |
| 2 | rounds, and a tool never runs on input that did not finish assembling. |
| 3 | |
| 4 | Every stream here is canned server-sent-event bytes (tests/ai_fakes.py), |
| 5 | split into small deltas so the parser has to reassemble text and tool |
| 6 | JSON exactly as it would from the provider. |
| 7 | """ |
| 8 | |
| 9 | import json |
| 10 | |
| 11 | import pytest |
| 12 | |
| 13 | import object_ai |
| 14 | import object_mcp |
| 15 | from ai_fakes import anthropic_message, sse, sse_stream, text_block |
| 16 | |
| 17 | |
| 18 | def _stream_run(streams, *, dispatched=None, sent=None, events=None, **kwargs): |
| 19 | def send_http_stream(url, headers, body): |
| 20 | if sent is not None: |
| 21 | sent.append(json.loads(body)) |
| 22 | return 200, iter(streams.pop(0)) |
| 23 | |
| 24 | def send_http(url, headers, body): |
| 25 | raise AssertionError("a streamed anthropic turn must not use send_http") |
| 26 | |
| 27 | def dispatch_tool(name, arguments): |
| 28 | if dispatched is not None: |
| 29 | dispatched.append((name, arguments)) |
| 30 | return {"http_status": 200, "response": {"results": ["n1"]}} |
| 31 | |
| 32 | def on_event(kind, data): |
| 33 | if events is not None: |
| 34 | events.append((kind, data)) |
| 35 | |
| 36 | kwargs.setdefault("tools", object_ai.mcp_tools_as_provider_tools( |
| 37 | ["global_search", "get_record"], object_mcp.TOOLS, service="anthropic")) |
| 38 | return object_ai.run_chat( |
| 39 | send_http=send_http, send_http_stream=send_http_stream, dispatch_tool=dispatch_tool, |
| 40 | on_event=on_event, stream=True, service="anthropic", model="claude-haiku-5-5", |
| 41 | key="sk-test", message="hi", **kwargs) |
| 42 | |
| 43 | |
| 44 | def test_iter_sse_follows_the_framing(): |
| 45 | lines = [b": comment\n", b"event: a\n", b"data: {\"x\":\n", b"data: 1}\n", b"\n", |
| 46 | b"data: plain\r\n", b"\r\n", b"event: tail\n", b"data: last\n"] |
| 47 | assert list(object_ai.iter_sse(lines)) == [ |
| 48 | ("a", '{"x":\n1}'), ("message", "plain"), ("tail", "last")] |
| 49 | |
| 50 | |
| 51 | def test_text_streams_as_deltas_and_the_reply_is_the_whole_text(): |
| 52 | events, sent = [], [] |
| 53 | result = _stream_run([sse_stream([("text", "Hello there, how can I help?")])], |
| 54 | events=events, sent=sent) |
| 55 | deltas = [data["text"] for kind, data in events if kind == "text"] |
| 56 | assert len(deltas) > 1 |
| 57 | assert "".join(deltas) == "Hello there, how can I help?" |
| 58 | assert result["reply"] == "Hello there, how can I help?" |
| 59 | assert result["stop_reason"] == "end_turn" |
| 60 | assert sent[0]["stream"] is True |
| 61 | |
| 62 | |
| 63 | def test_usage_takes_message_delta_totals_over_message_start(): |
| 64 | result = _stream_run([sse_stream( |
| 65 | [("text", "hi")], |
| 66 | usage={"input_tokens": 40, "output_tokens": 1, "cache_read_input_tokens": 900, |
| 67 | "cache_creation_input_tokens": 0}, |
| 68 | final_usage={"output_tokens": 25}, |
| 69 | )]) |
| 70 | assert result["usage"]["input_tokens"] == 40 |
| 71 | assert result["usage"]["output_tokens"] == 25 # cumulative, not 26 |
| 72 | assert result["usage"]["cache_read_input_tokens"] == 900 |
| 73 | assert result["usage"]["largest_prompt_tokens"] == 940 |
| 74 | |
| 75 | |
| 76 | def test_tools_run_between_streamed_rounds(): |
| 77 | events, dispatched, sent = [], [], [] |
| 78 | result = _stream_run([ |
| 79 | sse_stream([("thinking", "I should search.", "sig-abc"), |
| 80 | ("text", "Let me look."), |
| 81 | ("tool", "global_search", json.dumps({"query": "flywheel", "limit": 3}), |
| 82 | "toolu_1")], |
| 83 | stop_reason="tool_use"), |
| 84 | sse_stream([("text", "Found one note.")]), |
| 85 | ], events=events, dispatched=dispatched, sent=sent) |
| 86 | |
| 87 | assert dispatched == [("global_search", {"query": "flywheel", "limit": 3})] |
| 88 | assert result["reply"] == "Found one note." |
| 89 | assert result["rounds"] == 2 |
| 90 | assert result["tool_calls"] == [{"name": "global_search", |
| 91 | "arguments": {"query": "flywheel", "limit": 3}, |
| 92 | "http_status": 200}] |
| 93 | kinds = [kind for kind, _ in events] |
| 94 | assert kinds.index("tool_call") > kinds.index("text") |
| 95 | assert kinds[-1] == "text" # round two's text comes after the tool ran |
| 96 | |
| 97 | # Round two sends round one's content back whole: the thinking block |
| 98 | # with its signature, the text, and the tool_use with parsed input. |
| 99 | assistant = sent[1]["messages"][-2] |
| 100 | assert assistant["role"] == "assistant" |
| 101 | assert assistant["content"][0] == {"type": "thinking", "thinking": "I should search.", |
| 102 | "signature": "sig-abc"} |
| 103 | assert assistant["content"][1] == {"type": "text", "text": "Let me look."} |
| 104 | assert assistant["content"][2]["input"] == {"query": "flywheel", "limit": 3} |
| 105 | tool_result = sent[1]["messages"][-1]["content"][0] |
| 106 | assert tool_result["tool_use_id"] == "toolu_1" and "is_error" not in tool_result |
| 107 | |
| 108 | |
| 109 | @pytest.mark.parametrize("raw,problem", [ |
| 110 | ('{"query": "flyw', "not valid JSON"), |
| 111 | ('["query"]', "not a JSON object"), |
| 112 | ]) |
| 113 | def test_malformed_tool_json_is_never_dispatched(raw, problem): |
| 114 | dispatched, sent = [], [] |
| 115 | result = _stream_run([ |
| 116 | sse_stream([("tool", "global_search", raw, "toolu_bad")], stop_reason="tool_use"), |
| 117 | sse_stream([("text", "Sorry, retrying failed.")]), |
| 118 | ], dispatched=dispatched, sent=sent) |
| 119 | assert dispatched == [] |
| 120 | [entry] = result["tool_calls"] |
| 121 | assert entry["http_status"] == 400 and entry["error"] == "invalid_arguments" |
| 122 | tool_result = sent[1]["messages"][-1]["content"][0] |
| 123 | assert tool_result["is_error"] is True |
| 124 | assert problem in tool_result["content"] |
| 125 | # What goes back as the assistant's tool_use is still a valid object. |
| 126 | assert sent[1]["messages"][-2]["content"][0]["input"] == {} |
| 127 | |
| 128 | |
| 129 | def test_a_tool_with_no_arguments_streams_no_fragments_and_still_runs(): |
| 130 | dispatched = [] |
| 131 | _stream_run([ |
| 132 | sse_stream([("tool", "global_search", "", "toolu_2")], stop_reason="tool_use"), |
| 133 | sse_stream([("text", "ok")]), |
| 134 | ], dispatched=dispatched) |
| 135 | assert dispatched == [("global_search", {})] |
| 136 | |
| 137 | |
| 138 | def test_max_tokens_mid_tool_runs_nothing_and_says_cut_off(): |
| 139 | dispatched = [] |
| 140 | result = _stream_run([sse_stream( |
| 141 | [("text", "Writing the object"), ("tool", "global_search", '{"query": "fl', "toolu_3")], |
| 142 | stop_reason="max_tokens")], dispatched=dispatched, max_tokens=16384) |
| 143 | assert dispatched == [] |
| 144 | assert result["cut_off"] is True |
| 145 | assert "16384-token" in result["reply"] |
| 146 | |
| 147 | |
| 148 | def test_streamed_refusal_replaces_whatever_text_had_arrived(): |
| 149 | events = [] |
| 150 | result = _stream_run([sse_stream( |
| 151 | [("text", "Sure, step one")], stop_reason="refusal", |
| 152 | stop_details={"category": "cyber", "explanation": "Not this."})], events=events) |
| 153 | assert any(kind == "text" for kind, _ in events) # the preview did stream |
| 154 | assert result["reply"] == "The model declined to answer this request (cyber): Not this." |
| 155 | assert result["refusal"]["category"] == "cyber" |
| 156 | |
| 157 | |
| 158 | def test_streamed_pause_turn_resumes(): |
| 159 | sent = [] |
| 160 | result = _stream_run([ |
| 161 | sse_stream([("text", "Partway")], stop_reason="pause_turn"), |
| 162 | sse_stream([("text", " and done.")]), |
| 163 | ], sent=sent) |
| 164 | assert result["reply"] == " and done." |
| 165 | assert sent[1]["messages"][-1] == {"role": "assistant", |
| 166 | "content": [{"type": "text", "text": "Partway"}]} |
| 167 | |
| 168 | |
| 169 | def test_stream_error_event_raises_provider_error(): |
| 170 | lines = sse("message_start", {"type": "message_start", "message": {"usage": {}}}) |
| 171 | lines += sse("error", {"type": "error", "error": {"type": "overloaded_error", |
| 172 | "message": "Overloaded"}}) |
| 173 | with pytest.raises(object_ai.AIProviderError, match="Overloaded"): |
| 174 | _stream_run([lines]) |
| 175 | |
| 176 | |
| 177 | def test_stream_that_ends_early_raises_and_runs_no_tool(): |
| 178 | dispatched = [] |
| 179 | lines = sse_stream([("tool", "global_search", '{"query": "x"}', "toolu_4")], |
| 180 | stop_reason="tool_use") |
| 181 | cut = lines[: len(lines) - 6] # drop message_delta and message_stop |
| 182 | with pytest.raises(object_ai.AIProviderError, match="ended before"): |
| 183 | _stream_run([cut], dispatched=dispatched) |
| 184 | assert dispatched == [] |
| 185 | |
| 186 | |
| 187 | def test_http_error_on_a_stream_raises_with_the_providers_message(): |
| 188 | def send_http_stream(url, headers, body): |
| 189 | return 529, [json.dumps({"type": "error", |
| 190 | "error": {"message": "Overloaded, try later"}}).encode()] |
| 191 | |
| 192 | with pytest.raises(object_ai.AIProviderError, match="HTTP 529.*Overloaded"): |
| 193 | object_ai.run_chat(send_http=None, send_http_stream=send_http_stream, |
| 194 | dispatch_tool=lambda n, a: {}, stream=True, service="anthropic", |
| 195 | model="claude-haiku-5-5", key="sk-test", message="hi") |
| 196 | |
| 197 | |
| 198 | def test_openai_turns_are_not_streamed_but_still_report_text(): |
| 199 | events = [] |
| 200 | |
| 201 | def send_http(url, headers, body): |
| 202 | assert "stream" not in json.loads(body) |
| 203 | return 200, json.dumps({"choices": [{"message": {"content": "whole reply"}}]}).encode() |
| 204 | |
| 205 | result = object_ai.run_chat(send_http=send_http, dispatch_tool=lambda n, a: {}, |
| 206 | on_event=lambda k, d: events.append((k, d)), stream=True, |
| 207 | service="openai", model="gpt-5-mini", key="sk-test", |
| 208 | message="hi") |
| 209 | assert result["reply"] == "whole reply" |
| 210 | assert events == [("text", {"text": "whole reply"})] |
| 211 | |
| 212 | |
| 213 | def test_non_streamed_turns_are_unchanged_by_the_streaming_path(): |
| 214 | sent = [] |
| 215 | |
| 216 | def send_http(url, headers, body): |
| 217 | sent.append(json.loads(body)) |
| 218 | return anthropic_message([text_block("plain")]) |
| 219 | |
| 220 | result = object_ai.run_chat(send_http=send_http, dispatch_tool=lambda n, a: {}, |
| 221 | service="anthropic", model="claude-haiku-5-5", key="sk-test", |
| 222 | message="hi") |
| 223 | assert result["reply"] == "plain" |
| 224 | assert "stream" not in sent[0] |