okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (a3024ed10) into f-split-qa1: qa2's s3237-s3238 kept, my 21 strings renumbered s3260-s32808667a3dbf

main
4.2 KiB94 linesraw
1"""serve/test_anthropic_base_url.py - an Anthropic client reaches the server by the root address, and by the "/v1" one too.
2
3The Anthropic SDKs (and Claude Code) add /v1/messages to the base URL themselves. The app used to show the OpenAI-style base
4(.../v1) in its Anthropic tab, so those clients posted /v1/v1/messages and got a 404. The address is now shown without /v1, and
5the server accepts /v1/v1/messages (and /v1/v1/messages/count_tokens) as the same request, for people who already pasted the old one.
6
7Uses the real `anthropic` Python client against the mock-engine server (no network, no key). Skipped when the package is missing.
8
9    python -m unittest serve.test_anthropic_base_url -v
10"""
11from __future__ import annotations
12
13import http.client
14import json
15import sys
16import unittest
17from pathlib import Path
18
19sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
20from serve.frontend import ChatTemplate  # noqa: E402
21from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
22
23ROOT = Path(__file__).resolve().parents[1]
24
25try:
26    import anthropic
27except ImportError:                                           # pragma: no cover
28    anthropic = None
29
30
31REPLY = "<think>\nhm\n</think>\n\nhello from the mock"
32
33
34class AnthropicBase(unittest.TestCase):
35    @classmethod
36    def setUpClass(cls):
37        tok = ByteTokenizer()
38        cls.engine = MockEngine(tok, REPLY, max_context=4096)
39        cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
40        cls.httpd = serve(cls.svc, port=0)
41        cls.port = cls.httpd.server_address[1]
42        cls.root = f"http://127.0.0.1:{cls.port}"
43
44    @classmethod
45    def tearDownClass(cls):
46        cls.httpd.shutdown()
47        cls.httpd.server_close()
48
49    def raw(self, path, body):
50        c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
51        try:
52            c.request("POST", path, body=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
53            r = c.getresponse()
54            return r.status, json.loads(r.read() or b"{}")
55        finally:
56            c.close()
57
58    @unittest.skipIf(anthropic is None, "the anthropic package is not installed")
59    def test_sdk_with_the_root_address_works(self):
60        client = anthropic.Anthropic(base_url=self.root, api_key="not-needed", max_retries=0)
61        msg = client.messages.create(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}])
62        self.assertEqual(msg.type, "message")
63        self.assertIn("hello", "".join(b.text for b in msg.content if b.type == "text"))
64
65    @unittest.skipIf(anthropic is None, "the anthropic package is not installed")
66    def test_sdk_with_the_old_v1_address_works_through_the_alias(self):
67        client = anthropic.Anthropic(base_url=self.root + "/v1", api_key="not-needed", max_retries=0)
68        msg = client.messages.create(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}])
69        self.assertEqual(msg.type, "message")
70        self.assertIn("hello", "".join(b.text for b in msg.content if b.type == "text"))
71
72    @unittest.skipIf(anthropic is None, "the anthropic package is not installed")
73    def test_sdk_streaming_through_the_alias(self):
74        client = anthropic.Anthropic(base_url=self.root + "/v1", api_key="not-needed", max_retries=0)
75        with client.messages.stream(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}]) as stream:
76            text = "".join(stream.text_stream)
77        self.assertIn("hello", text)
78
79    def test_count_tokens_alias(self):
80        body = {"model": "strata", "messages": [{"role": "user", "content": "hi"}]}
81        code, real = self.raw("/v1/messages/count_tokens", body)
82        code2, aliased = self.raw("/v1/v1/messages/count_tokens", body)
83        self.assertEqual((code, code2), (200, 200))
84        self.assertEqual(real, aliased)
85
86    def test_only_the_two_messages_paths_are_aliased(self):
87        body = {"model": "strata", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}
88        for path in ("/v1/v1/chat/completions", "/v1/v1/responses", "/v1/v1/v1/messages", "/v1/v2/messages"):
89            code, _ = self.raw(path, body)
90            self.assertEqual(code, 404, path)
91
92
93if __name__ == "__main__":
94    unittest.main()