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_chat_stream_endpoint.py · 7.9 KB · 170 lines
| 1 | """POST /api/ai/chat with "stream": true answers in server-sent events. |
| 2 | |
| 3 | The streamed turn is the same turn: tools run between rounds through the |
| 4 | server's own routing with the caller's credentials (so a tool the caller |
| 5 | may not use is refused exactly as on the JSON path), and the turn is |
| 6 | priced and recorded by the same code before the final ``done`` event. |
| 7 | Anything that refuses a turn before the provider is called stays an |
| 8 | ordinary JSON error with its real status. |
| 9 | """ |
| 10 | |
| 11 | import json |
| 12 | |
| 13 | import object_ai |
| 14 | import object_records |
| 15 | import object_server |
| 16 | from ai_fakes import ( |
| 17 | PRICES_HEADER, |
| 18 | chat_server, |
| 19 | install_fake_transport, |
| 20 | sse_stream, |
| 21 | ) |
| 22 | from test_object_server import raw_request, request, save_permission_policy, write_records |
| 23 | |
| 24 | |
| 25 | def _events(payload: bytes): |
| 26 | return [(kind, json.loads(data)) |
| 27 | for kind, data in object_ai.iter_sse(payload.splitlines(keepends=True))] |
| 28 | |
| 29 | |
| 30 | def _post_stream(headers, body): |
| 31 | status, response_headers, payload = raw_request( |
| 32 | "/api/ai/chat", method="POST", headers=headers, |
| 33 | body=json.dumps({**body, "stream": True}).encode()) |
| 34 | return status, response_headers, _events(payload) |
| 35 | |
| 36 | |
| 37 | def test_text_streams_then_done_carries_the_json_response(tmp_path, monkeypatch): |
| 38 | data_dir, headers = chat_server( |
| 39 | tmp_path, monkeypatch, |
| 40 | prices_tsv=PRICES_HEADER + "p\tanthropic\tclaude-haiku-5-5\t10\t50\t\t\t100000\t2026-12-01\n") |
| 41 | seen = [] |
| 42 | install_fake_transport(monkeypatch, [("sse", sse_stream( |
| 43 | [("text", "Streaming works fine.")], |
| 44 | usage={"input_tokens": 100_000, "output_tokens": 1}, |
| 45 | final_usage={"output_tokens": 1_000_000}))], seen) |
| 46 | |
| 47 | status, response_headers, events = _post_stream(headers, {"message": "hi"}) |
| 48 | |
| 49 | assert status == 200 |
| 50 | assert response_headers[b"content-type"].startswith(b"text/event-stream") |
| 51 | assert response_headers[b"cache-control"] == b"no-cache" |
| 52 | kinds = [kind for kind, _ in events] |
| 53 | assert kinds[-1] == "done" and kinds.count("done") == 1 |
| 54 | assert "".join(d["text"] for k, d in events if k == "text") == "Streaming works fine." |
| 55 | done = events[-1][1] |
| 56 | assert done["status"] == "ok" |
| 57 | assert done["reply"] == "Streaming works fine." |
| 58 | assert done["model"] == "anthropic:claude-haiku-5-5" |
| 59 | # 100K in @ 10c/M + 1M out @ 50c/M = 1c + 50c, priced by the same code |
| 60 | # as JSON turns (and within the row's 100K-token prompt limit). |
| 61 | assert done["usage"]["cost_cents"] == 51 |
| 62 | assert seen[0]["body"]["stream"] is True |
| 63 | [row] = object_records.read_collection_records("ai_usage", base_dir=data_dir) |
| 64 | assert row["tokens_out"] == "1000000" and row["cost_cents"] == "51" |
| 65 | |
| 66 | |
| 67 | def test_tools_run_between_rounds_with_the_callers_permissions(tmp_path, monkeypatch): |
| 68 | data_dir = tmp_path / "data" |
| 69 | write_records(data_dir, "notes", "id\tcontent\nn1\tflywheel plan\n") |
| 70 | schema_file = data_dir / "schemas" / "notes.json" |
| 71 | schema_file.parent.mkdir(parents=True, exist_ok=True) |
| 72 | schema_file.write_text(json.dumps( |
| 73 | {"fields": [{"name": "id"}, {"name": "content"}], "search": {"fields": ["content"]}})) |
| 74 | save_permission_policy(data_dir, {"access_mode": "role_based", "rules": [ |
| 75 | {"effect": "allow", "principal": "registered", "actions": ["read"], |
| 76 | "collection": "notes", "reason": "signed-in users read notes"}]}) |
| 77 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 78 | data_dir, headers = chat_server(tmp_path, monkeypatch) |
| 79 | seen = [] |
| 80 | install_fake_transport(monkeypatch, [ |
| 81 | ("sse", sse_stream([ |
| 82 | ("text", "Checking."), |
| 83 | ("tool", "global_search", json.dumps({"query": "flywheel"}), "t1"), |
| 84 | # An admin-only tool: a signed-in user's credentials do not reach it. |
| 85 | ("tool", "get_admin_status", "{}", "t2"), |
| 86 | ], stop_reason="tool_use")), |
| 87 | ("sse", sse_stream([("text", "Your note says flywheel plan.")])), |
| 88 | ], seen) |
| 89 | |
| 90 | status, _, events = _post_stream(headers, {"message": "find flywheel", |
| 91 | "tools": ["global_search", "get_admin_status"]}) |
| 92 | |
| 93 | assert status == 200 |
| 94 | tool_events = [d for k, d in events if k == "tool_call"] |
| 95 | assert [e["name"] for e in tool_events] == ["global_search", "get_admin_status"] |
| 96 | assert tool_events[0]["http_status"] == 200 |
| 97 | assert tool_events[1]["http_status"] in (401, 403) |
| 98 | kinds = [k for k, _ in events] |
| 99 | assert kinds.index("tool_call") < kinds.index("done") |
| 100 | done = events[-1][1] |
| 101 | assert done["reply"] == "Your note says flywheel plan." |
| 102 | assert done["rounds"] == 2 |
| 103 | assert [c["http_status"] for c in done["tool_calls"]] == [ |
| 104 | e["http_status"] for e in tool_events] |
| 105 | # The real search result went back to the model in round two. |
| 106 | results = seen[1]["body"]["messages"][-1]["content"] |
| 107 | assert "n1" in results[0]["content"] |
| 108 | |
| 109 | |
| 110 | def test_a_tool_outside_the_offered_subset_is_refused_while_streaming(tmp_path, monkeypatch): |
| 111 | _, headers = chat_server(tmp_path, monkeypatch) |
| 112 | install_fake_transport(monkeypatch, [ |
| 113 | ("sse", sse_stream([("tool", "delete_record", |
| 114 | json.dumps({"collection": "notes", "record_id": "n1"}), "t1")], |
| 115 | stop_reason="tool_use")), |
| 116 | ("sse", sse_stream([("text", "I could not.")])), |
| 117 | ]) |
| 118 | status, _, events = _post_stream(headers, {"message": "delete", "tools": ["get_record"]}) |
| 119 | assert status == 200 |
| 120 | [tool_event] = [d for k, d in events if k == "tool_call"] |
| 121 | assert tool_event["http_status"] == 400 |
| 122 | |
| 123 | |
| 124 | def test_a_provider_error_mid_turn_ends_in_an_error_event(tmp_path, monkeypatch): |
| 125 | data_dir, headers = chat_server(tmp_path, monkeypatch) |
| 126 | broken = sse_stream([("text", "Half")])[:-6] # no message_delta / message_stop |
| 127 | install_fake_transport(monkeypatch, [("sse", broken)]) |
| 128 | status, _, events = _post_stream(headers, {"message": "hi"}) |
| 129 | assert status == 200 |
| 130 | kind, data = events[-1] |
| 131 | assert kind == "error" |
| 132 | assert data["http_status"] == 502 and "ended before" in data["error"] |
| 133 | assert "done" not in [k for k, _ in events] |
| 134 | # Same as the JSON path: a failed turn writes no usage row. |
| 135 | assert object_records.read_collection_records("ai_usage", base_dir=data_dir) == [] |
| 136 | |
| 137 | |
| 138 | def test_refusals_before_the_provider_stay_json_errors(tmp_path, monkeypatch): |
| 139 | _, headers = chat_server(tmp_path, monkeypatch) |
| 140 | install_fake_transport(monkeypatch, []) |
| 141 | status, _, body = request("/api/ai/chat", method="POST", headers=headers, |
| 142 | body=json.dumps({"message": "hi", "stream": "yes"}).encode()) |
| 143 | assert status == 400 and "stream" in body["error"] |
| 144 | status, _, body = request( |
| 145 | "/api/ai/chat", method="POST", headers=headers, |
| 146 | body=json.dumps({"message": "hi", "stream": True, |
| 147 | "model": "openai:gpt-5-mini"}).encode()) |
| 148 | assert status == 400 and "No openai key" in body["error"] |
| 149 | |
| 150 | |
| 151 | def test_streamed_builder_turns_get_the_streaming_budget(tmp_path, monkeypatch): |
| 152 | _, headers = chat_server(tmp_path, monkeypatch) |
| 153 | seen = [] |
| 154 | install_fake_transport(monkeypatch, [("sse", sse_stream([("text", "ok")]))], seen) |
| 155 | _post_stream(headers, {"message": "build", "tools": ["create_object"]}) |
| 156 | assert seen[0]["body"]["max_tokens"] == 16384 |
| 157 | assert seen[0]["body"]["output_config"] == {"effort": "high"} |
| 158 | |
| 159 | |
| 160 | def test_the_json_endpoint_is_unchanged_when_stream_is_absent(tmp_path, monkeypatch): |
| 161 | _, headers = chat_server(tmp_path, monkeypatch) |
| 162 | seen = [] |
| 163 | install_fake_transport(monkeypatch, [(200, json.dumps({ |
| 164 | "content": [{"type": "text", "text": "plain"}], "stop_reason": "end_turn", |
| 165 | "usage": {"input_tokens": 1, "output_tokens": 1}}).encode())], seen) |
| 166 | status, response_headers, body = request("/api/ai/chat", method="POST", headers=headers, |
| 167 | body=json.dumps({"message": "hi"}).encode()) |
| 168 | assert status == 200 and body["reply"] == "plain" |
| 169 | assert response_headers[b"content-type"].startswith(b"application/json") |
| 170 | assert "stream" not in seen[0]["body"] |