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.
ai_fakes.py · 7.4 KB · 180 lines
| 1 | """Canned provider traffic for AI chat tests. No test here touches a network. |
| 2 | |
| 3 | Anthropic Messages API responses are built as plain dicts and returned as |
| 4 | bytes; streamed responses are built as the server-sent-event byte lines |
| 5 | the provider sends, so the stream parser is exercised on real framing |
| 6 | (``event:`` / ``data:`` / blank line), not on pre-parsed objects. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import json |
| 12 | from pathlib import Path |
| 13 | |
| 14 | import object_server |
| 15 | from test_object_server import create_identity_session, enable_admin_token, request |
| 16 | |
| 17 | AI_USAGE_FIELDS = [ |
| 18 | {"name": "id"}, |
| 19 | {"name": "owner_id", "type": "text"}, |
| 20 | {"name": "provider", "type": "text", "required": True}, |
| 21 | {"name": "model", "type": "text", "required": True}, |
| 22 | {"name": "tokens_in", "type": "int", "required": True}, |
| 23 | {"name": "tokens_out", "type": "int", "required": True}, |
| 24 | {"name": "tokens_cache_read", "type": "int"}, |
| 25 | {"name": "tokens_cache_write", "type": "int"}, |
| 26 | {"name": "cost_cents", "type": "int"}, |
| 27 | {"name": "created_at", "type": "datetime", "read_only": True}, |
| 28 | ] |
| 29 | |
| 30 | |
| 31 | def anthropic_message(content, *, stop_reason="end_turn", usage=None, stop_details=None): |
| 32 | payload = { |
| 33 | "type": "message", |
| 34 | "role": "assistant", |
| 35 | "content": content, |
| 36 | "stop_reason": stop_reason, |
| 37 | "usage": usage or {"input_tokens": 10, "output_tokens": 5}, |
| 38 | } |
| 39 | if stop_details is not None: |
| 40 | payload["stop_details"] = stop_details |
| 41 | return 200, json.dumps(payload).encode() |
| 42 | |
| 43 | |
| 44 | def text_block(text): |
| 45 | return {"type": "text", "text": text} |
| 46 | |
| 47 | |
| 48 | def tool_block(name, arguments, block_id="call-1"): |
| 49 | return {"type": "tool_use", "id": block_id, "name": name, "input": arguments} |
| 50 | |
| 51 | |
| 52 | def sse(event, data): |
| 53 | """One server-sent event as the provider frames it.""" |
| 54 | return [f"event: {event}\n".encode(), f"data: {json.dumps(data)}\n".encode(), b"\n"] |
| 55 | |
| 56 | |
| 57 | def sse_stream(blocks, *, stop_reason="end_turn", usage=None, final_usage=None, |
| 58 | stop_details=None, chunk=7): |
| 59 | """A full streamed message: ``blocks`` are ("text", str) or |
| 60 | ("tool", name, raw_json_string, id) or ("thinking", str, signature). |
| 61 | Text and tool JSON are split into ``chunk``-sized deltas so the parser |
| 62 | must reassemble them.""" |
| 63 | start_usage = usage or {"input_tokens": 10, "output_tokens": 1} |
| 64 | lines = sse("message_start", {"type": "message_start", "message": { |
| 65 | "id": "msg_1", "type": "message", "role": "assistant", "content": [], |
| 66 | "stop_reason": None, "usage": start_usage}}) |
| 67 | lines += sse("ping", {"type": "ping"}) |
| 68 | for index, block in enumerate(blocks): |
| 69 | kind = block[0] |
| 70 | if kind == "text": |
| 71 | lines += sse("content_block_start", {"type": "content_block_start", "index": index, |
| 72 | "content_block": {"type": "text", "text": ""}}) |
| 73 | text = block[1] |
| 74 | for i in range(0, len(text), chunk): |
| 75 | lines += sse("content_block_delta", { |
| 76 | "type": "content_block_delta", "index": index, |
| 77 | "delta": {"type": "text_delta", "text": text[i:i + chunk]}}) |
| 78 | elif kind == "thinking": |
| 79 | lines += sse("content_block_start", {"type": "content_block_start", "index": index, |
| 80 | "content_block": {"type": "thinking", "thinking": ""}}) |
| 81 | lines += sse("content_block_delta", { |
| 82 | "type": "content_block_delta", "index": index, |
| 83 | "delta": {"type": "thinking_delta", "thinking": block[1]}}) |
| 84 | lines += sse("content_block_delta", { |
| 85 | "type": "content_block_delta", "index": index, |
| 86 | "delta": {"type": "signature_delta", "signature": block[2]}}) |
| 87 | else: |
| 88 | _, name, raw, block_id = block |
| 89 | lines += sse("content_block_start", {"type": "content_block_start", "index": index, |
| 90 | "content_block": {"type": "tool_use", "id": block_id, |
| 91 | "name": name, "input": {}}}) |
| 92 | for i in range(0, len(raw), chunk): |
| 93 | lines += sse("content_block_delta", { |
| 94 | "type": "content_block_delta", "index": index, |
| 95 | "delta": {"type": "input_json_delta", "partial_json": raw[i:i + chunk]}}) |
| 96 | lines += sse("content_block_stop", {"type": "content_block_stop", "index": index}) |
| 97 | delta = {"stop_reason": stop_reason, "stop_sequence": None} |
| 98 | if stop_details is not None: |
| 99 | delta["stop_details"] = stop_details |
| 100 | lines += sse("message_delta", {"type": "message_delta", "delta": delta, |
| 101 | "usage": final_usage or {"output_tokens": 5}}) |
| 102 | lines += sse("message_stop", {"type": "message_stop"}) |
| 103 | return lines |
| 104 | |
| 105 | |
| 106 | class FakeResponse: |
| 107 | """Stands in for urllib's response: read() for JSON, iteration for SSE.""" |
| 108 | |
| 109 | def __init__(self, status, body=b"", lines=None): |
| 110 | self.status = status |
| 111 | self._body = body |
| 112 | self._lines = lines |
| 113 | self.closed = False |
| 114 | |
| 115 | def read(self): |
| 116 | if self._lines is not None: |
| 117 | return b"".join(self._lines) |
| 118 | return self._body |
| 119 | |
| 120 | def __iter__(self): |
| 121 | lines = self._lines if self._lines is not None else self._body.splitlines(keepends=True) |
| 122 | return iter(lines) |
| 123 | |
| 124 | def close(self): |
| 125 | self.closed = True |
| 126 | |
| 127 | def __enter__(self): |
| 128 | return self |
| 129 | |
| 130 | def __exit__(self, *args): |
| 131 | self.close() |
| 132 | return False |
| 133 | |
| 134 | |
| 135 | def install_fake_transport(monkeypatch, responses, seen=None): |
| 136 | """Patch urlopen inside object_server. ``responses`` items are |
| 137 | (status, bytes) for JSON or ("sse", [lines]) for a stream.""" |
| 138 | |
| 139 | def fake_urlopen(request_obj, timeout=None): |
| 140 | if seen is not None: |
| 141 | seen.append({"url": request_obj.full_url, |
| 142 | "headers": dict(request_obj.header_items()), |
| 143 | "body": json.loads(request_obj.data)}) |
| 144 | item = responses.pop(0) |
| 145 | if item[0] == "sse": |
| 146 | return FakeResponse(200, lines=item[1]) |
| 147 | return FakeResponse(item[0], body=item[1]) |
| 148 | |
| 149 | monkeypatch.setattr(object_server.urllib.request, "urlopen", fake_urlopen) |
| 150 | |
| 151 | |
| 152 | def chat_server(tmp_path, monkeypatch, *, prices_tsv=None, user="dan"): |
| 153 | """A data dir with ai_usage (+ optional ai_prices), chat enabled, a |
| 154 | signed-in user with a stored anthropic key. Returns (data_dir, headers).""" |
| 155 | from test_object_server import write_records |
| 156 | |
| 157 | data_dir = tmp_path / "data" |
| 158 | if prices_tsv is not None: |
| 159 | write_records(data_dir, "ai_prices", prices_tsv) |
| 160 | schema_file = Path(data_dir) / "schemas" / "ai_usage.json" |
| 161 | schema_file.parent.mkdir(parents=True, exist_ok=True) |
| 162 | schema_file.write_text(json.dumps({"fields": AI_USAGE_FIELDS})) |
| 163 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 164 | monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true") |
| 165 | enable_admin_token(monkeypatch) |
| 166 | token, _ = create_identity_session({"user_id": user}) |
| 167 | headers = [("authorization", f"Bearer {token}"), ("content-type", "application/json")] |
| 168 | request( |
| 169 | f"/identity/users/{user}/service-keys", method="PUT", |
| 170 | body=json.dumps({"service": "anthropic", "key": "sk-test-not-real"}).encode(), |
| 171 | headers=headers, |
| 172 | ) |
| 173 | return data_dir, headers |
| 174 | |
| 175 | |
| 176 | PRICES_HEADER = ( |
| 177 | "id\tprovider\tmodel\tinput_per_million_cents\toutput_per_million_cents\t" |
| 178 | "cache_read_per_million_cents\tcache_write_per_million_cents\t" |
| 179 | "price_max_prompt_tokens\teffective_date\n" |
| 180 | ) |