From 79232bd7195ae32086ff83a4b2d327ebec5111b2 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Fri, 20 Nov 2026 00:57:39 -0500 Subject: [PATCH] test(mistral): check the request and stream shapes at the wire `wire.body` exposes the request Mistral is sent, and `wire.reducer` the stream reader. A property sends generated histories (empty assistant messages, tool calls with foreign ids, replayed reasoning, efforts on and off) and checks Mistral's shapes: only documented fields, the session as prompt_cache_key, no empty assistant message, nine-character call ids that still pair with their results, no user message straight after results, and thinking only to a request that reasons. Deleted e2e/mistral_test.py (6 tests, 3.1 s); what now catches each defect: - empty assistant messages and foreign call ids from the proxy -> any_history_is_sent_in_the_shape_mistral_takes, tool_call_ids_become_mistral_ids_stably - undocumented request fields, cache key, effort -> any_history_is_sent_in_the_shape_mistral_takes - thinking chunks streamed and replayed -> a_thinking_stream_reads_as_thinking_then_text, thinking_replays_as_typed_chunks_only_when_the_request_reasons - tool images after a bridge -> a_tool_results_images_follow_a_bridge - the picker's chat models -> the_picker_lists_chat_models_that_call_tools - a login key serving a plain profile -> accounts_test a_plain_profile_skips_a_key_saved_for_another_endpoint --- e2e/areas.toml | 11 - e2e/mistral_test.py | 384 ---------------- extensions/mistral/gleam.toml | 2 + extensions/mistral/manifest.toml | 7 + .../src/albedo_ext_mistral/extension.gleam | 2 +- .../mistral/src/albedo_ext_mistral/wire.gleam | 9 +- .../test/albedo_ext_mistral/wire_test.gleam | 420 ++++++++++++++++++ .../test/albedo_ext_mistral_test.gleam | 6 +- 8 files changed, 441 insertions(+), 400 deletions(-) delete mode 100644 e2e/mistral_test.py create mode 100644 extensions/mistral/test/albedo_ext_mistral/wire_test.gleam diff --git a/e2e/areas.toml b/e2e/areas.toml index cd2571f6e..5cbe1f9e6 100644 --- a/e2e/areas.toml +++ b/e2e/areas.toml @@ -464,12 +464,10 @@ # OpenAI-compatible /models lists and the host cache of them. "packages/albedo_sdk/src/albedo_sdk/model_lists.gleam" = [ "model_catalogs_test.py", - "mistral_test.py", "network_test.py", ] "packages/albedo_openai/src/albedo_openai/catalog.gleam" = [ "model_catalogs_test.py", - "mistral_test.py", ] "packages/albedo_http/src/albedo_http/proxy.gleam" = ["network_test.py"] "packages/albedo_http/src/albedo_http/route.gleam" = ["network_test.py"] @@ -720,7 +718,6 @@ "compaction_progress_test.py", "provider_protocols_test.py", "model_catalogs_test.py", - "mistral_test.py", ] "packages/albedo_bytes/src/albedo_bytes/ids.gleam" = [ "webhooks_test.py", @@ -731,7 +728,6 @@ "packages/albedo_sdk/src/albedo_sdk/key_environment.gleam" = [ "proxy_test.py", "github_copilot_test.py", - "mistral_test.py", "perplexity_test.py", "opencode_go_login_test.py", "bedrock_effort_catalog_test.py", @@ -740,7 +736,6 @@ "packages/albedo_env/src/albedo_env.gleam" = [ "proxy_test.py", "github_copilot_test.py", - "mistral_test.py", "perplexity_test.py", "opencode_go_login_test.py", "bedrock_effort_catalog_test.py", @@ -750,7 +745,6 @@ "credentials_test.py", "accounts_test.py", "github_copilot_test.py", - "mistral_test.py", "opencode_go_login_test.py", "provider_protocols_test.py", "model_catalogs_test.py", @@ -758,7 +752,6 @@ "packages/albedo_sdk/src/albedo_sdk/oauth.gleam" = [ "github_copilot_test.py", "opencode_go_login_test.py", - "mistral_test.py", "integration_test.py", "context_test.py", "prompt_test.py", @@ -811,7 +804,6 @@ "extensions/anthropic_api/src/albedo_ext_anthropic_api/**" = [ "anthropic_api_test.py", ] -"extensions/mistral/src/albedo_ext_mistral/**" = ["mistral_test.py"] "packages/albedo_sdk/src/albedo_sdk/auth_accounts.gleam" = [ "account_rotation_test.py", "accounts_test.py", @@ -910,7 +902,6 @@ "prompt_test.py", "opencode_zen_test.py", "github_copilot_test.py", - "mistral_test.py", "perplexity_test.py", ] "extensions/antigravity/src/albedo_ext_antigravity/**" = [ @@ -928,7 +919,6 @@ "github_copilot_test.py", "bedrock_effort_catalog_test.py", "fast_mode_test.py", - "mistral_test.py", "opencode_go_login_test.py", "model_catalogs_test.py", "provider_protocols_test.py", @@ -1014,7 +1004,6 @@ "github_copilot_test.py", "bedrock_effort_catalog_test.py", "fast_mode_test.py", - "mistral_test.py", "opencode_go_login_test.py", "model_catalogs_test.py", "provider_protocols_test.py", diff --git a/e2e/mistral_test.py b/e2e/mistral_test.py deleted file mode 100644 index b31f545f8..000000000 --- a/e2e/mistral_test.py +++ /dev/null @@ -1,384 +0,0 @@ -"""Mistral is a model provider over its own Chat Completions API. - -Mistral refuses any request field it does not document and has two shapes of -its own, so the assertions here are on what the daemon sends and how it reads -the answer: no `stream_options` or `max_completion_tokens`, the session as -`prompt_cache_key`, the session's reasoning effort, thinking that streams as -typed content chunks and goes back the same way, and tool call ids replayed -as Mistral's nine letters and digits. The picker lists only the models the -API marks as chatting and calling tools, and a key saved by /login serves a -profile that pins none. - -The saved key is global, so the class is exclusive. -""" - -import json -import unittest -import urllib.parse - -from integration_support import IntegrationScenario - -from harness import ( - Albedo, - Provider, - Reply, - error, - exclusive_class, - operation_id, - python, - strip_timestamp, - text, -) - -MODEL = "mistral-medium-latest" - -KEY = "mistral-fixture-key" - -API_MODELS = { - "object": "list", - "data": [ - { - "id": MODEL, - "capabilities": {"completion_chat": True, "function_calling": True}, - }, - { - "id": "mistral-embed", - "capabilities": {"completion_chat": False, "function_calling": False}, - }, - { - "id": "mistral-ocr-latest", - "capabilities": {"completion_chat": True, "function_calling": False}, - }, - ], -} - -# models.dev's `mistral` namespace, which names no endpoint: the extension's -# own catalog is what answers for it at a Mistral profile's base url. -MODELS_DEV = { - "mistral": { - "id": "mistral", - "name": "Mistral", - "env": ["MISTRAL_API_KEY"], - "models": { - MODEL: { - "id": MODEL, - "limit": {"context": 262144, "output": 262144}, - "reasoning_options": [{"type": "effort", "values": ["none", "high"]}], - } - }, - } -} - - -def chunk(delta, finish=None, usage=None): - value = { - "id": "mistral-fixture", - "object": "chat.completion.chunk", - "model": MODEL, - "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], - } - if usage: - value["usage"] = usage - return value - - -def thinking(text): - return {"type": "thinking", "thinking": [{"type": "text", "text": text}]} - - -# A reasoning answer as Mistral streams it: content starts as a list of -# thinking chunks, holds both kinds at the turn, then becomes plain text. -THOUGHTFUL = Reply( - "text", - events=[ - # Mistral's delta also carries fields the shared reducer does not read. - chunk( - { - "role": "assistant", - "content": [thinking("six sevens")], - "index": 0, - "tool_call_id": None, - } - ), - chunk({"content": [thinking(" are 42"), {"type": "text", "text": "It is "}]}), - chunk({"content": "42."}), - chunk( - {"content": ""}, - "stop", - { - "prompt_tokens": 100, - "completion_tokens": 10, - "total_tokens": 110, - "prompt_tokens_details": {"cached_tokens": 64}, - }, - ), - ], -) - - -# A python cell that shows a 1x1 PNG it builds itself. -TINY_PNG = ( - "import struct, zlib\n" - "def part(kind, data):\n" - " body = kind + data\n" - " return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body))\n" - "png = (b'\\x89PNG\\r\\n\\x1a\\n'\n" - " + part(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0))\n" - " + part(b'IDAT', zlib.compress(b'\\x00\\xff\\x00\\x00'))\n" - " + part(b'IEND', b''))\n" - "show_image(png)\n" -) - - -def scripting(replies): - def reply(request): - return replies.pop(0) if replies else text("done") - - return reply - - -@exclusive_class -class MistralTests(IntegrationScenario): - def start(self, replies, *, key=True, fixture=None): - provider = Provider(fixture or scripting(list(replies)), catalog=API_MODELS) - self.addCleanup(provider.close) - profile = { - "extension": "mistral", - "baseUrl": provider.url, - "model": MODEL, - "protocol": "chat_completions", - } - if key: - profile["apiKey"] = KEY - - def offline(app): - (app.home / "models.json").write_text(json.dumps(MODELS_DEV)) - - app = Albedo(provider, providers={"mistral": profile}, prepare=offline) - app.__enter__() - self.addCleanup(app.__exit__, None, None, None) - return app, provider - - def ask(self, app, session, prompt): - app.prompt(session, prompt).close() - app.idle(session) - - def test_proxy_drops_empty_assistant_messages_without_breaking_tool_history(self): - def enforce(request): - for message in request["messages"]: - if ( - message["role"] == "assistant" - and not message.get("content") - and not message.get("tool_calls") - ): - return error( - 400, "Assistant message must have content or tool_calls" - ) - return text("accepted") - - app, provider = self.start([], fixture=enforce) - app.write_extensions({"enabled": {"proxy": True}}) - calls = [ - { - "id": identity, - "type": "function", - "function": {"name": "lookup", "arguments": "{}"}, - } - for identity in ["external-call", "ABCDEF123", "é1234567", "e\u03011234567"] - ] - expected_ids = ["8621fb20b", "ABCDEF123", "0c7cbf77e", "62e4e14b1"] - history = [ - {"role": "user", "content": "first"}, - {"role": "assistant", "content": None, "refusal": None}, - {"role": "user", "content": "second"}, - {"role": "assistant", "content": "", "tool_calls": []}, - {"role": "assistant", "content": None, "tool_calls": calls}, - *[ - {"role": "tool", "tool_call_id": call["id"], "content": "found"} - for call in calls - ], - {"role": "assistant", "content": ""}, - {"role": "user", "content": "continue"}, - ] - with app.api( - "/extensions/proxy/v1/chat/completions", - { - "model": "mistral/" + MODEL, - "messages": history, - "reasoning_effort": "none", - "stream": True, - }, - ) as response: - chunks = [ - json.loads(line.removeprefix("data: ")) - for line in response.read().decode().splitlines() - if line.startswith("data: ") and line != "data: [DONE]" - ] - self.assertFalse([chunk for chunk in chunks if "error" in chunk], chunks) - self.assertEqual( - "".join( - choice["delta"].get("content", "") - for chunk in chunks - for choice in chunk.get("choices", []) - ), - "accepted", - ) - [sent] = provider.requests - messages = sent["request"]["messages"] - self.assertEqual( - [message["role"] for message in messages], - ["user", "user", "assistant", *["tool"] * len(calls), "assistant", "user"], - ) - self.assertEqual(messages[0]["content"], "first") - self.assertEqual(messages[1]["content"], "second") - self.assertEqual( - [call["id"] for call in messages[2]["tool_calls"]], expected_ids - ) - self.assertEqual( - [ - message["tool_call_id"] - for message in messages - if message["role"] == "tool" - ], - expected_ids, - ) - self.assertIsNone(messages[2]["content"]) - self.assertFalse({"reasoning", "reasoning_content"} & messages[2].keys()) - self.assertEqual(messages[-2]["content"], "I have processed the tool results.") - - def test_the_request_carries_only_what_mistral_documents(self): - app, provider = self.start([text("an answer")]) - session = app.session() - self.ask(app, session, "hello") - [request] = provider.requests - self.assertTrue(request["path"].endswith("/chat/completions"), request["path"]) - self.assertEqual(request["authorization"], f"Bearer {KEY}") - body = request["request"] - self.assertTrue(body["stream"]) - for absent in ("stream_options", "max_completion_tokens", "store"): - self.assertNotIn(absent, body) - self.assertEqual(body["prompt_cache_key"], session) - # models.dev lists none and high for this model but no default, so - # Mistral decides until the session picks a level. - self.assertNotIn("reasoning_effort", body) - msg = body["messages"][-1] - self.assertEqual(msg["role"], "user") - self.assertEqual(strip_timestamp(msg["content"]), "hello") - - self.change(app, session, {"effort": "high"}) - self.ask(app, session, "again") - self.assertEqual(provider.requests[-1]["request"]["reasoning_effort"], "high") - - def test_thinking_chunks_stream_and_replay_as_mistral_reads_them(self): - app, provider = self.start( - [ - python("print(6 * 7)", reasoning="let me compute"), - THOUGHTFUL, - text("", reasoning="thinking only"), - ] - ) - session = app.session() - # Thinking is replayed only to a request that asks for reasoning. - self.change(app, session, {"effort": "high"}) - self.ask(app, session, "multiply") - answers = [ - entry - for entry in app.history(session)["items"] - if entry["kind"] == "assistant" - ] - self.assertEqual( - answers[-1]["content"], [{"kind": "text", "text": "It is 42."}] - ) - - messages = provider.requests[1]["request"]["messages"] - [call] = [m for m in messages if m["role"] == "assistant"] - [result] = [m for m in messages if m["role"] == "tool"] - # The fixture's own id is no Mistral id; its replacement is stable, so - # the call and its result still pair. - call_id = call["tool_calls"][0]["id"] - self.assertRegex(call_id, r"^[A-Za-z0-9]{9}$") - self.assertEqual(result["tool_call_id"], call_id) - self.assertIn("42", result["content"]) - self.assertEqual(call["content"], [thinking("let me compute")]) - self.assertEqual(set(call), {"role", "content", "tool_calls"}) - - self.ask(app, session, "and doubled?") - messages = provider.requests[2]["request"]["messages"] - replayed = [m for m in messages if m["role"] == "assistant"][-1] - self.assertEqual( - replayed["content"], - [thinking("six sevens are 42"), {"type": "text", "text": "It is 42."}], - ) - for message in messages: - self.assertFalse( - {"reasoning_content", "reasoning", "refusal"} & set(message), message - ) - - self.change(app, session, {"effort": "none"}) - self.ask(app, session, "answer without thinking") - messages = provider.requests[-1]["request"]["messages"] - assistants = [message for message in messages if message["role"] == "assistant"] - self.assertEqual(provider.requests[-1]["request"]["reasoning_effort"], "none") - [tool_call] = [message for message in assistants if message.get("tool_calls")] - self.assertIsNone(tool_call["content"]) - contents = [message["content"] for message in assistants] - self.assertIn("It is 42.", contents) - self.assertNotIn("thinking only", contents) - self.assertTrue( - all(content is None or isinstance(content, str) for content in contents) - ) - self.assertTrue( - all( - not ({"reasoning", "reasoning_content"} & message.keys()) - for message in assistants - ) - ) - - def test_a_tool_results_images_follow_a_bridge_after_the_results(self): - # Mistral takes no user message straight after tool results, so the - # images a result carries come after a short assistant bridge. - app, provider = self.start([python(TINY_PNG), text("a dot")]) - self.ask(app, app.session(), "draw") - messages = provider.requests[1]["request"]["messages"] - roles = [m["role"] for m in messages] - tool = roles.index("tool") - self.assertEqual(roles[tool + 1 :], ["assistant", "user"]) - self.assertEqual( - messages[tool + 1]["content"], "I have processed the tool results." - ) - self.assertIsInstance(messages[tool]["content"], str) - parts = messages[tool + 2]["content"] - self.assertEqual( - parts[0]["text"], - f"Images from tool call {messages[tool]['tool_call_id']}:", - ) - self.assertTrue(parts[1]["image_url"]["url"].startswith("data:image/png")) - - def test_the_picker_lists_the_chat_models_that_call_tools(self): - app, provider = self.start([]) - query = urllib.parse.urlencode( - {"provider": "mistral", "endpoint": provider.url} - ) - with app.api(f"/models?{query}") as response: - listed = [item["id"] for item in json.load(response)["items"]] - self.assertEqual(listed, [MODEL]) - - def test_a_key_saved_by_login_serves_a_profile_that_pins_none(self): - app, provider = self.start([text("keyed")], key=False) - with app.api( - f"/auth/keys/{operation_id()}", - { - "provider": "mistral", - "endpoint": provider.url, - "api_key": KEY, - "label": "fixture", - }, - method="PUT", - ) as response: - self.assertEqual(json.load(response)["kind"], "key") - self.ask(app, app.session(), "hello") - self.assertEqual(provider.requests[0]["authorization"], f"Bearer {KEY}") - - -if __name__ == "__main__": - unittest.main() diff --git a/extensions/mistral/gleam.toml b/extensions/mistral/gleam.toml index b53ed800c..f80dadc86 100644 --- a/extensions/mistral/gleam.toml +++ b/extensions/mistral/gleam.toml @@ -23,3 +23,5 @@ albedo_sse = { path = "../../packages/albedo_sse" } [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" +qcheck = ">= 1.0.5 and < 2.0.0" +albedo_property = { path = "../../packages/albedo_property" } diff --git a/extensions/mistral/manifest.toml b/extensions/mistral/manifest.toml index 4e5417fc9..9b7a5b7c0 100644 --- a/extensions/mistral/manifest.toml +++ b/extensions/mistral/manifest.toml @@ -21,6 +21,7 @@ packages = [ { name = "albedo_openai", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_http", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_sse", "gleam_json", "gleam_stdlib"], source = "local", path = "../../packages/albedo_openai" }, { name = "albedo_ports", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_stdlib"], source = "local", path = "../../packages/albedo_ports" }, { name = "albedo_process", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_protect", "gleam_erlang", "gleam_otp", "gleam_stdlib"], source = "local", path = "../../packages/albedo_process" }, + { name = "albedo_property", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_env", "albedo_protect", "gleam_erlang", "gleam_stdlib", "qcheck"], source = "local", path = "../../packages/albedo_property" }, { name = "albedo_protect", version = "0.1.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], source = "local", path = "../../packages/albedo_protect" }, { name = "albedo_sdk", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_bytes", "albedo_clock", "albedo_env", "albedo_file", "albedo_http", "albedo_image", "albedo_json", "albedo_model", "albedo_model_stream", "albedo_oauth", "albedo_openai", "albedo_ports", "albedo_process", "albedo_protect", "albedo_sqlite", "albedo_web", "gleam_crypto", "gleam_erlang", "gleam_http", "gleam_json", "gleam_otp", "gleam_stdlib", "mist", "sqlight", "yamerl"], source = "local", path = "../../packages/albedo_sdk" }, { name = "albedo_sqlite", version = "0.1.0", build_tools = ["gleam"], requirements = ["albedo_clock", "albedo_process", "esqlite", "gleam_erlang", "gleam_otp", "gleam_stdlib", "sqlight"], source = "local", path = "../../packages/albedo_sqlite" }, @@ -33,13 +34,17 @@ packages = [ { name = "gleam_http", version = "4.4.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "F065CE9941A7756ABBAEAE7F9F32A96CAD29DA3311A381DB2D926EA8E8C156DC" }, { name = "gleam_json", version = "3.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "44FDAA8847BE8FC48CA7A1C089706BD54BADCC4C45B237A992EDDF9F2CDB2836" }, { name = "gleam_otp", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "DE4CA6850842F0266EE95317A25DD6A0A0F20CDFAB7C0ADC2E63251D7C3C72EC" }, + { name = "gleam_regexp", version = "1.1.1", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_regexp", source = "hex", outer_checksum = "9C215C6CA84A5B35BB934A9B61A9A306EC743153BE2B0425A0D032E477B062A9" }, { name = "gleam_stdlib", version = "1.0.5", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "CEE5B6C076A85B45F60C585F4316C63EC8B7127C119D5738C3958A9C4D50404E" }, + { name = "gleam_yielder", version = "1.1.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_yielder", source = "hex", outer_checksum = "8E4E4ECFA7982859F430C57F549200C7749823C106759F4A19A78AEA6687717A" }, { name = "gleeunit", version = "1.11.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "EC31ABA74256AEA531EDF8169931D775BBB384FED0A8A1BDC4DD9354E3E21826" }, { name = "glisten", version = "9.0.1", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_otp", "gleam_stdlib", "logging"], otp_app = "glisten", source = "hex", outer_checksum = "7795AA50830656F3A0316A6B26595F893C83272DA901B3405E31339CAA31A10B" }, { name = "gramps", version = "6.0.1", build_tools = ["gleam"], requirements = ["gleam_crypto", "gleam_erlang", "gleam_http", "gleam_stdlib"], otp_app = "gramps", source = "hex", outer_checksum = "D55636072DEE173F6586A5679D3C02EC7A0DE3F8646B78C351B72908FF223DF7" }, { name = "hpack_erl", version = "0.3.0", build_tools = ["rebar3"], requirements = [], otp_app = "hpack", source = "hex", outer_checksum = "D6137D7079169D8C485C6962DFE261AF5B9EF60FBC557344511C1E65E3D95FB0" }, { name = "logging", version = "1.5.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "logging", source = "hex", outer_checksum = "BC5F18CE5DD9686100229FE5409BDC3DD5C46D5A7DF2F804AD2D8F0DD6C5060E" }, { name = "mist", version = "6.0.3", build_tools = ["gleam"], requirements = ["exception", "gleam_erlang", "gleam_http", "gleam_otp", "gleam_stdlib", "glisten", "gramps", "hpack_erl", "logging"], source = "local", path = "../../vendor/mist" }, + { name = "prng", version = "6.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "prng", source = "hex", outer_checksum = "7FE3879E13150248BD370469205ED07B9404DD90670FEBB8CD0E7643707C420E" }, + { name = "qcheck", version = "1.0.5", build_tools = ["gleam"], requirements = ["exception", "gleam_regexp", "gleam_stdlib", "gleam_yielder", "prng"], otp_app = "qcheck", source = "hex", outer_checksum = "D27C12074776EC95F082EE56E0FC74685506B6EE26176F194D10F0322A39AC11" }, { name = "sqlight", version = "1.2.0", build_tools = ["gleam"], requirements = ["esqlite", "gleam_stdlib"], otp_app = "sqlight", source = "hex", outer_checksum = "841768D0A81107EE2DB46B949354F284A68B2E8098315C28A1FE3C07D206C17A" }, { name = "yamerl", version = "0.10.0", build_tools = ["rebar3"], requirements = [], otp_app = "yamerl", source = "hex", outer_checksum = "346ADB2963F1051DC837A2364E4ACF6EB7D80097C0F53CBDC3046EC8EC4B4E6E" }, ] @@ -53,9 +58,11 @@ albedo_model = { path = "../../packages/albedo_model" } albedo_model_stream = { path = "../../packages/albedo_model_stream" } albedo_models_dev = { path = "../../packages/albedo_models_dev" } albedo_openai = { path = "../../packages/albedo_openai" } +albedo_property = { path = "../../packages/albedo_property" } albedo_sdk = { path = "../../packages/albedo_sdk" } albedo_sse = { path = "../../packages/albedo_sse" } gleam_crypto = { version = ">= 1.0.0 and < 2.0.0" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } gleeunit = { version = ">= 1.0.0 and < 2.0.0" } +qcheck = { version = ">= 1.0.5 and < 2.0.0" } diff --git a/extensions/mistral/src/albedo_ext_mistral/extension.gleam b/extensions/mistral/src/albedo_ext_mistral/extension.gleam index 3f8505b3a..29ad3c691 100644 --- a/extensions/mistral/src/albedo_ext_mistral/extension.gleam +++ b/extensions/mistral/src/albedo_ext_mistral/extension.gleam @@ -246,7 +246,7 @@ fn models( /// The ids that chat and call tools, sorted and deduplicated. Invalid JSON and /// a body without a `data` list are both refused as the wrong shape. -fn chat_model_ids(body: BitArray) -> Result(List(String), String) { +pub fn chat_model_ids(body: BitArray) -> Result(List(String), String) { use rows <- result.try( json.parse_bits(body, decode.at(["data"], decode.list(decode.dynamic))) |> result.replace_error("unexpected /models response shape"), diff --git a/extensions/mistral/src/albedo_ext_mistral/wire.gleam b/extensions/mistral/src/albedo_ext_mistral/wire.gleam index cda4754f4..5166da727 100644 --- a/extensions/mistral/src/albedo_ext_mistral/wire.gleam +++ b/extensions/mistral/src/albedo_ext_mistral/wire.gleam @@ -205,9 +205,16 @@ fn replay( } } +/// The body Mistral is sent for `request` in `session`: the request in +/// Mistral's shape, encoded with only the fields Mistral documents. +pub fn body(session: String, request: Request) -> Result(StringTree, Error) { + use request <- result.try(prepare(request)) + encode(session, ChatCompletions, request) +} + /// The shared Chat Completions reducer, fed each chunk once its content /// chunks are read as text and reasoning. -fn reducer() -> Reducer { +pub fn reducer() -> Reducer { albedo_model_stream.wrap( stream.new(ChatCompletions), fn(state, data) { stream.feed(state, sse.Event("", chunk(data))) }, diff --git a/extensions/mistral/test/albedo_ext_mistral/wire_test.gleam b/extensions/mistral/test/albedo_ext_mistral/wire_test.gleam new file mode 100644 index 000000000..089fb037c --- /dev/null +++ b/extensions/mistral/test/albedo_ext_mistral/wire_test.gleam @@ -0,0 +1,420 @@ +//// What albedo sends Mistral and how it reads Mistral's stream. Mistral +//// refuses any request field it does not document and has shapes of its +//// own: no `stream_options` or `max_completion_tokens`, `max_tokens` instead, +//// the session as `prompt_cache_key`, no assistant message without content or +//// calls, tool call ids of nine letters and digits, no user message straight +//// after tool results, and thinking as typed content chunks. The defects are +//// a refused request (a field, an empty message, a bad id, a user turn after +//// results), a tool result that no longer pairs with its call, and thinking +//// lost or sent to a request that does not reason. + +import albedo_ext_mistral/extension as mistral +import albedo_ext_mistral/wire +import albedo_model as types +import albedo_model_stream +import albedo_property +import gleam/bit_array +import gleam/dict +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{None, Some} +import gleam/result +import gleam/string +import gleam/string_tree +import qcheck.{type Generator} + +const documented = [ + "model", "messages", "stream", "n", "tools", "tool_choice", + "parallel_tool_calls", "max_tokens", "temperature", "top_p", "stop", + "reasoning_effort", "response_format", "prompt_cache_key", +] + +const bridge = "I have processed the tool results." + +/// Any history Mistral is sent keeps to its documented fields and shapes, +/// and every tool result still pairs with its call. +pub fn any_history_is_sent_in_the_shape_mistral_takes_test() -> Nil { + use #(history, effort) <- albedo_property.run( + 300, + qcheck.tuple2(history(), qcheck.option_from(effort())), + ) + let request = + types.Request( + "mistral-medium-latest", + Some("be brief"), + history, + [], + Some(1000), + types.Options(..types.defaults, effort: effort, cache: True), + ) + let assert Ok(sent) = wire.body("session-1", request) + let assert Ok(body) = + json.parse( + string_tree.to_string(sent), + decode.dict(decode.string, decode.dynamic), + ) + dict.each(body, fn(key, _) { + assert list.contains(documented, key) + as { key <> " is not a Mistral field" } + }) + assert dict.get(body, "prompt_cache_key") == Ok(dynamic.string("session-1")) + let assert Ok(messages) = dict.get(body, "messages") + let assert Ok(messages) = decode.run(messages, decode.list(decode.dynamic)) + let thinking = case effort { + None | Some(types.NoReasoning) -> False + Some(_) -> True + } + check_messages(messages, thinking, [], "") +} + +/// Walks the messages in order with the call ids seen so far and the role +/// before. +fn check_messages( + messages: List(Dynamic), + thinking: Bool, + calls: List(String), + previous: String, +) -> Nil { + case messages { + [] -> Nil + [message, ..rest] -> { + let role = text(message, ["role"]) + let keys = + decode.run(message, decode.dict(decode.string, decode.dynamic)) + |> result.map(dict.keys) + |> result.unwrap([]) + assert !list.any(keys, list.contains( + ["reasoning", "reasoning_content", "refusal"], + _, + )) + assert !{ previous == "tool" && role == "user" } + as "a user message straight after tool results" + let calls = case role { + "assistant" -> { + let ids = + decode.run( + message, + decode.optional_field( + "tool_calls", + [], + decode.list(decode.at(["id"], decode.string)), + decode.success, + ), + ) + |> result.unwrap([]) + list.each(ids, fn(id) { + assert string.byte_size(id) == 9 && alphanumeric(id) + as { id <> " is no Mistral tool call id" } + }) + let content = + decode.run( + message, + decode.optional_field( + "content", + None, + decode.optional(decode.string), + decode.success, + ), + ) + let empty = content == Ok(None) || content == Ok(Some("")) + assert !{ empty && ids == [] } as "an assistant message with nothing" + case thinking { + True -> Nil + False -> { + assert result.is_ok(decode.run( + message, + decode.at(["content"], decode.optional(decode.string)), + )) + as "thinking sent to a request that does not reason" + } + } + list.append(calls, ids) + } + "tool" -> { + assert list.contains(calls, text(message, ["tool_call_id"])) + as "a tool result without its call" + calls + } + _ -> calls + } + check_messages(rest, thinking, calls, role) + } + } +} + +/// A call id that is not nine letters and digits is replaced by a stable one, +/// so the call and its result keep pairing across requests. +pub fn tool_call_ids_become_mistral_ids_stably_test() -> Nil { + let ids = ["external-call", "ABCDEF123", "é1234567", "e\u{301}1234567"] + let history = + list.flatten([ + [types.User("first")], + [replay_with_calls(ids)], + list.map(ids, fn(id) { types.ToolOutput(id, "found", []) }), + [types.User("continue")], + ]) + let assert [assistant, ..tools] = sent_messages(history, None) |> list.drop(2) + let expected = ["8621fb20b", "ABCDEF123", "0c7cbf77e", "62e4e14b1"] + assert decode.run( + assistant, + decode.at(["tool_calls"], decode.list(decode.at(["id"], decode.string))), + ) + == Ok(expected) + assert list.take(tools, 4) |> list.map(text(_, ["tool_call_id"])) == expected +} + +/// The images a tool result carries follow the results, after the bridge. +pub fn a_tool_results_images_follow_a_bridge_test() -> Nil { + let assert Ok(image) = types.image("image/png", "aGk=", 1, 1, 2) + let messages = + sent_messages( + [ + types.User("draw"), + replay_with_calls(["ABCDEF123"]), + types.ToolOutput("ABCDEF123", "", [image]), + ], + None, + ) + let roles = list.map(messages, text(_, ["role"])) + assert roles == ["system", "user", "assistant", "tool", "assistant", "user"] + let assert [_, _, _, tool, said, images] = messages + assert text(tool, ["content"]) == "(see attached image)" + assert text(said, ["content"]) == bridge + assert decode.run(images, decode.at(["content"], decode.list(decode.dynamic))) + |> result.map(list.length) + == Ok(2) +} + +/// Thinking goes back as Mistral's typed chunks to a request that reasons, +/// and is left out of one that does not. +pub fn thinking_replays_as_typed_chunks_only_when_the_request_reasons_test() -> Nil { + let assert Ok(item) = + json.parse( + "{\"role\":\"assistant\",\"content\":\"It is 42.\",\"reasoning_content\":\"six sevens are 42\"}", + types.replay_decoder(types.ChatCompletions), + ) + let history = [ + types.User("multiply"), + types.Replay(item), + types.User("again"), + ] + let assert [_, _, reasoning, _] = sent_messages(history, Some(types.High)) + assert decode.run( + reasoning, + decode.at(["content"], decode.list(decode.at(["type"], decode.string))), + ) + == Ok(["thinking", "text"]) + let assert [_, _, plain, _] = sent_messages(history, Some(types.NoReasoning)) + assert text(plain, ["content"]) == "It is 42." +} + +/// Mistral streams thinking as typed content chunks, then plain text. +pub fn a_thinking_stream_reads_as_thinking_then_text_test() -> Nil { + let thinking = fn(text) { + "{\"type\":\"thinking\",\"thinking\":[{\"type\":\"text\",\"text\":\"" + <> text + <> "\"}]}" + } + let chunk = fn(delta, finish) { + "{\"id\":\"m\",\"object\":\"chat.completion.chunk\",\"model\":\"m\",\"choices\":[{\"index\":0,\"delta\":" + <> delta + <> ",\"finish_reason\":" + <> finish + <> "}]}" + } + let frames = [ + chunk( + "{\"role\":\"assistant\",\"content\":[" + <> thinking("six sevens") + <> "],\"index\":0,\"tool_call_id\":null}", + "null", + ), + chunk( + "{\"content\":[" + <> thinking(" are 42") + <> ",{\"type\":\"text\",\"text\":\"It is \"}]}", + "null", + ), + chunk("{\"content\":\"42.\"}", "null"), + chunk("{\"content\":\"\"}", "\"stop\""), + "[DONE]", + ] + let events = read(wire.reducer(), frames, []) + let thought = + list.filter_map(events, fn(event) { + case event { + types.ThinkingDelta(text) -> Ok(text) + _ -> Error(Nil) + } + }) + let said = + list.filter_map(events, fn(event) { + case event { + types.TextDelta(_, _, text) -> Ok(text) + _ -> Error(Nil) + } + }) + assert string.concat(thought) == "six sevens are 42" + assert string.concat(said) == "It is 42." +} + +/// The picker lists the models the API marks as chatting and calling tools. +pub fn the_picker_lists_chat_models_that_call_tools_test() -> Nil { + let body = + "{\"object\":\"list\",\"data\":[{\"id\":\"mistral-medium-latest\",\"capabilities\":{\"completion_chat\":true,\"function_calling\":true}},{\"id\":\"mistral-embed\",\"capabilities\":{\"completion_chat\":false,\"function_calling\":false}},{\"id\":\"mistral-ocr-latest\",\"capabilities\":{\"completion_chat\":true,\"function_calling\":false}}]}" + assert mistral.chat_model_ids(bit_array.from_string(body)) + == Ok(["mistral-medium-latest"]) +} + +// ---- helpers ----------------------------------------------------------------- + +/// Every event the reducer emits for `frames`, which must end in a turn. +fn read( + reducer: albedo_model_stream.Reducer, + frames: List(String), + seen: List(types.Event), +) -> List(types.Event) { + let assert [data, ..rest] = frames as "the stream ended without a turn" + let assert Ok(#(next, events, turn)) = reducer.feed(data) + let seen = list.append(seen, events) + case turn { + Some(_) -> seen + None -> read(next, rest, seen) + } +} + +fn sent_messages( + history: List(types.Input), + effort: option.Option(types.Effort), +) -> List(Dynamic) { + let request = + types.Request( + "mistral-medium-latest", + Some("be brief"), + history, + [], + Some(1000), + types.Options(..types.defaults, effort: effort), + ) + let assert Ok(sent) = wire.body("session-1", request) + let assert Ok(messages) = + json.parse( + string_tree.to_string(sent), + decode.at(["messages"], decode.list(decode.dynamic)), + ) + messages +} + +fn replay_with_calls(ids: List(String)) -> types.Input { + let calls = + list.map(ids, fn(id) { + json.object([ + #("id", json.string(id)), + #("type", json.string("function")), + #( + "function", + json.object([ + #("name", json.string("lookup")), + #("arguments", json.string("{}")), + ]), + ), + ]) + }) + let assert Ok(item) = + json.parse( + json.to_string( + json.object([ + #("role", json.string("assistant")), + #("content", json.null()), + #("tool_calls", json.preprocessed_array(calls)), + ]), + ), + types.replay_decoder(types.ChatCompletions), + ) + types.Replay(item) +} + +fn text(value: Dynamic, path: List(String)) -> String { + decode.run(value, decode.at(path, decode.string)) |> result.unwrap("") +} + +fn alphanumeric(text: String) -> Bool { + string.to_graphemes(text) + |> list.all(fn(c) { + string.contains( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", + c, + ) + }) +} + +// ---- generators -------------------------------------------------------------- + +fn history() -> Generator(List(types.Input)) { + qcheck.generic_list(input(), qcheck.bounded_int(0, 8)) + |> qcheck.map(paired) +} + +/// Inputs as a session holds them: each tool result follows the call that +/// asked for it. +fn paired(inputs: List(types.Input)) -> List(types.Input) { + list.flat_map(inputs, fn(input) { + case input { + types.ToolOutput(id, text, images) -> [ + replay_with_calls([id]), + types.ToolOutput(id, text, images), + ] + other -> [other] + } + }) +} + +fn input() -> Generator(types.Input) { + qcheck.from_generators(qcheck.map(say(), types.User), [ + qcheck.map(say(), types.Assistant), + qcheck.map2(call_id(), say(), fn(id, text) { + types.ToolOutput(id, text, []) + }), + qcheck.map2(say(), qcheck.option_from(say()), fn(text, reasoning) { + let fields = [ + #("role", json.string("assistant")), + #("content", case text { + "" -> json.null() + text -> json.string(text) + }), + ..case reasoning { + Some(r) -> [#("reasoning_content", json.string(r))] + None -> [] + } + ] + let assert Ok(item) = + json.parse( + json.to_string(json.object(fields)), + types.replay_decoder(types.ChatCompletions), + ) + types.Replay(item) + }), + ]) +} + +fn say() -> Generator(String) { + one_of(["", "hi", "é", "42"]) +} + +fn call_id() -> Generator(String) { + one_of(["external-call", "ABCDEF123", "call_" <> int.to_string(7), "é1234567"]) +} + +fn effort() -> Generator(types.Effort) { + qcheck.from_generators(qcheck.return(types.NoReasoning), [ + qcheck.return(types.High), + ]) +} + +fn one_of(values: List(String)) -> Generator(String) { + let assert [first, ..rest] = values + qcheck.from_generators(qcheck.return(first), list.map(rest, qcheck.return)) +} diff --git a/extensions/mistral/test/albedo_ext_mistral_test.gleam b/extensions/mistral/test/albedo_ext_mistral_test.gleam index 347092e65..5665cb0c2 100644 --- a/extensions/mistral/test/albedo_ext_mistral_test.gleam +++ b/extensions/mistral/test/albedo_ext_mistral_test.gleam @@ -1,6 +1,6 @@ -//// The sign-in unit test uses albedo's shared OAuth test helpers, so it stays in -//// albedo's `test/harness/`. The Mistral end-to-end scenarios -//// (`e2e/mistral_test.py`) cover the extension through a daemon. +//// The Mistral extension's tests live under `test/albedo_ext_mistral/`: key +//// selection, and the request and stream shapes of its wire. Sign-in uses +//// albedo's shared OAuth test helpers, so it stays in albedo's own tests. import gleeunit -- knotmirror 0.0.1