https://arxiv.org/abs/2606.28344. The end of web parsing. The beginning of scalable pixel-native search. link: https://pixelrag.ai/
feat(eval): add MiniMax Flash reader support (#181)
Octopus6f56a1afd195
diff --git a/eval/README.md b/eval/README.mdindex dcf1d08..ce9180d 100644--- a/eval/README.md+++ b/eval/README.md@@ -236,29 +236,37 @@ flag or `--api-base`.## MiniMax readers-Set `MINIMAX_API_KEY` and select either registered model ID. The model context length-must be passed explicitly so retrieval truncation uses the correct limit.+Set `MINIMAX_API_KEY` and select `MiniMax-M3.1-Flash` (recommended) or `MiniMax-M3`.+The model context length must be passed explicitly so retrieval truncation uses+the correct limit. Explicit legacy `MiniMax-M2.7` selections still resolve for+existing evaluation configurations.| Model ID | Context window | Input modalities | Thinking || --- | ---: | --- | --- |+| `MiniMax-M3.1-Flash` | 1,000,000 | text, image, video | adaptive only || `MiniMax-M3` | 1,000,000 | text, image, video | adaptive or disabled |-| `MiniMax-M2.7` | 204,800 | text | always on |++Flash supports up to 524,288 output tokens, including thinking. The reader keeps+its existing generation budget unless `--max-tokens` is supplied. Flash uses the+API's default `max` reasoning effort; `--no-think` is rejected for direct Flash+requests. Direct M3 requests support `--no-think`. ReAct preserves the complete+MiniMax assistant message, including separate reasoning, between retrieval turns.Pricing is in USD per million tokens:| Model ID | Service tier | Input range | Input | Output | Cache read | Cache write || --- | --- | --- | ---: | ---: | ---: | ---: |+| `MiniMax-M3.1-Flash` | default | all | $0.15 | $0.60 | $0.015 | - || `MiniMax-M3` | standard | <= 512k input tokens | $0.30 | $1.20 | $0.06 | - || `MiniMax-M3` | standard | > 512k input tokens | $0.60 | $2.40 | $0.12 | - || `MiniMax-M3` | priority | <= 512k input tokens | $0.45 | $1.80 | $0.09 | - || `MiniMax-M3` | priority | > 512k input tokens | $0.90 | $3.60 | $0.18 | - |-| `MiniMax-M2.7` | standard | all | $0.30 | $1.20 | $0.06 | $0.375 |```bashexport MINIMAX_API_KEY=your-api-keyuv run python run_bench.py \--task simpleqa \- --model MiniMax-M3 \+ --model MiniMax-M3.1-Flash \--model-context-length 1000000 \--num-examples 1```diff --git a/eval/lib/llm.py b/eval/lib/llm.pyindex 5f250bd..ef2e703 100644--- a/eval/lib/llm.py+++ b/eval/lib/llm.py@@ -31,10 +31,17 @@ except ImportError:HttpOptions = NoneContent = None+from .model_config import MINIMAX_ENDPOINTS, MINIMAX_MODELSfrom .retrieval import RetrievalResultlogger = logging.getLogger(__name__)++def _minimax_key(model: str) -> str:+ """Registry key for a model name, matching get_model_config's lookup."""+ return model.lower().rsplit("/", 1)[-1]++# Some modern reasoning models deprecate `temperature` (Claude Opus 4.7+, some# GPT-5 variants). Both backend paths consult this list, so a newly released# model is added in one place rather than drifting between them.@@ -381,7 +388,7 @@ def _encode_images_to_content(def build_react_messages(query: str,retrieval_results: list[RetrievalResult],- assistant_responses: list[str],+ assistant_responses: list[str | dict],encode_image_fn=None,prompt_version: str = "v1",is_last_turn: bool = False,@@ -453,8 +460,11 @@ def build_react_messages(# Add assistant response if we have one for this turnif turn_idx < len(assistant_responses):+ response = assistant_responses[turn_idx]messages.append(- {"role": "assistant", "content": assistant_responses[turn_idx]}+ response+ if isinstance(response, dict)+ else {"role": "assistant", "content": response})return messages@@ -487,6 +497,26 @@ class LLMClient:# Kept for the LiteLLM path (module-level SDK, no persistent client object).self.api_key = api_keyself.api_base = api_base+ # Match the same way get_model_config does -- on the last path segment --+ # so a vendor-prefixed spelling like "MiniMax/MiniMax-M3.1-Flash" (used by+ # this module's own tests) resolves identically here and at the+ # assistant-message branch in _generate_openai. Comparing the bare string+ # made the two disagree: is_direct_minimax was False while the message+ # branch fired, so Flash silently got the legacy thinking payload.+ self.is_direct_minimax = (+ not use_litellm+ and _minimax_key(model) in MINIMAX_MODELS+ and (api_base or "").rstrip("/")+ in {endpoint["api_base"] for endpoint in MINIMAX_ENDPOINTS.values()}+ )+ if (+ self.is_direct_minimax+ and _minimax_key(model) == "minimax-m3.1-flash"+ and enable_thinking is False+ ):+ raise ValueError(+ "MiniMax-M3.1-Flash requires adaptive thinking; omit --no-think."+ )print(f"context length model: {max_context_tokens}")# LiteLLM routes every provider through one SDK call using a@@ -748,9 +778,16 @@ class LLMClient:if not drops_temperature:kwargs["temperature"] = self.temperatureif self.enable_thinking is not None:- kwargs["extra_body"] = {- "chat_template_kwargs": {"enable_thinking": self.enable_thinking}- }+ if self.is_direct_minimax:+ kwargs["extra_body"] = {+ "thinking": {+ "type": "adaptive" if self.enable_thinking else "disabled"+ }+ }+ else:+ kwargs["extra_body"] = {+ "chat_template_kwargs": {"enable_thinking": self.enable_thinking}+ }response = await self.client.chat.completions.create(**kwargs)generated_text = response.choices[0].message.content@@ -763,6 +800,16 @@ class LLMClient:"total_tokens": response.usage.total_tokens,}+ if _minimax_key(self.model) in MINIMAX_MODELS:+ # ReAct must replay Flash's separate reasoning_content together with+ # the assistant content and any tool calls, not just the answer text.+ # Underscore-prefixed: `usage` is serialized verbatim as each+ # record's token accounting, so anything here that is not a token+ # count must be strippable. run_bench drops _-keys before writing.+ usage["_assistant_message"] = response.choices[0].message.model_dump(+ exclude_none=True+ )+return generated_text, usageasync def _generate_litellm(self, messages: list[dict]) -> tuple[str, dict]:diff --git a/eval/lib/model_config.py b/eval/lib/model_config.pyindex 0b89844..a9c6234 100644--- a/eval/lib/model_config.py+++ b/eval/lib/model_config.py@@ -7,14 +7,39 @@ import osfrom typing import Any, DictMINIMAX_MODELS = {+ "minimax-m3.1-flash": "MiniMax-M3.1-Flash","minimax-m3": "MiniMax-M3",- "minimax-m2.7": "MiniMax-M2.7",}+# Resolve explicit legacy selections without advertising them as current models.+MINIMAX_LEGACY_MODELS = {"minimax-m2.7": "MiniMax-M2.7"}+MINIMAX_MODEL_METADATA = {+ "minimax-m3.1-flash": {+ "context_window": 1_000_000,+ "max_output_tokens": 524_288,+ "pricing_usd_per_million_tokens": {+ "input": 0.15,+ "output": 0.6,+ "cache_read": 0.015,+ "cache_write": None,+ },+ "input_modalities": ["text", "image", "video"],+ "thinking": ["adaptive"],+ "reasoning_effort": ["low", "medium", "high", "xhigh", "max"],+ "default_reasoning_effort": "max",+ },"minimax-m3": {"context_window": 1_000_000,+ # Standard-tier pricing up to 512k input tokens."pricing_usd_per_million_tokens": {+ "input": 0.3,+ "output": 1.2,+ "cache_read": 0.06,+ "cache_write": None,+ },+ "long_context_pricing_usd_per_million_tokens": {+ "input_range": ">512k","input": 0.6,"output": 2.4,"cache_read": 0.12,@@ -99,7 +124,9 @@ def get_model_config(model_name: str) -> Dict[str, Any]:# MiniMax models (OpenAI-compatible API)minimax_key = model_lower.rsplit("/", 1)[-1]- minimax_model = MINIMAX_MODELS.get(minimax_key)+ minimax_model = MINIMAX_MODELS.get(minimax_key) or MINIMAX_LEGACY_MODELS.get(+ minimax_key+ )if minimax_model:# The two bases are independent overrides for gateways and proxies, so# resolve them first and consult a region only for whichever was leftdiff --git a/eval/run_bench.py b/eval/run_bench.pyindex ec3dd25..6e6a4d4 100644--- a/eval/run_bench.py+++ b/eval/run_bench.py@@ -326,7 +326,7 @@ async def process_example("dataset_name": task_name,"retrieval_type": retrieval_result.retrieval_type,"has_retrieval_content": retrieval_result.has_content,- "usage": usage,+ "usage": _token_usage(usage),"success": True,"timing": {"retrieval_time": retrieval_time,@@ -511,6 +511,11 @@ def _hits_to_retrieval_result(hits: list[dict]) -> "RetrievalResult": # noqa: F)+def _token_usage(usage: dict) -> dict:+ """Token counts only: drop private keys carried alongside them."""+ return {k: v for k, v in usage.items() if not k.startswith("_")}++async def process_example_react(llm_client: LLMClient,retriever,@@ -584,7 +589,9 @@ async def process_example_react(# Extract search query and do another roundsearch_query = match.group(1).strip()all_search_queries.append(search_query)- assistant_responses.append(generated_text)+ assistant_responses.append(+ usage.get("_assistant_message", generated_text)+ )logger.info(f"ReAct [{example_id}] turn {turn + 1}: searching '{search_query[:80]}'")@@ -622,7 +629,12 @@ async def process_example_react(],}if turn_idx < len(assistant_responses):- turn_info["assistant_response"] = assistant_responses[turn_idx]+ response = assistant_responses[turn_idx]+ turn_info["assistant_response"] = (+ response.get("content", "")+ if isinstance(response, dict)+ else response+ )elif turn_idx == len(retrieval_results) - 1:# Last turn: the final_response is the answerturn_info["assistant_response"] = final_response@@ -643,7 +655,7 @@ async def process_example_react("dataset_name": task_name,"retrieval_type": "local_api_react","has_retrieval_content": any(r.has_content for r in retrieval_results),- "usage": usage,+ "usage": _token_usage(usage),"success": True,"react_turns": turns_used,"react_search_queries": all_search_queries,diff --git a/tests/test_eval_model_config.py b/tests/test_eval_model_config.pyindex 3ecb6a7..76bcc79 100644--- a/tests/test_eval_model_config.py+++ b/tests/test_eval_model_config.py@@ -12,6 +12,9 @@ get_model_config = MODEL_CONFIG["get_model_config"]@pytest.mark.parametrize(("model_name", "model_id"),[+ ("MiniMax-M3.1-Flash", "MiniMax-M3.1-Flash"),+ ("MiniMax/MiniMax-M3.1-Flash", "MiniMax-M3.1-Flash"),+ ("minimax-m3.1-flash", "MiniMax-M3.1-Flash"),("MiniMax-M3", "MiniMax-M3"),("MiniMax/MiniMax-M3", "MiniMax-M3"),("MiniMax-M2.7", "MiniMax-M2.7"),@@ -85,7 +88,14 @@ def test_minimax_model_config_supports_endpoint_and_key_overrides(monkeypatch):1_000_000,["text", "image", "video"],["adaptive", "disabled"],- {"input": 0.6, "output": 2.4, "cache_read": 0.12, "cache_write": None},+ {"input": 0.3, "output": 1.2, "cache_read": 0.06, "cache_write": None},+ ),+ (+ "MiniMax-M3.1-Flash",+ 1_000_000,+ ["text", "image", "video"],+ ["adaptive"],+ {"input": 0.15, "output": 0.6, "cache_read": 0.015, "cache_write": None},),("MiniMax-M2.7",@@ -107,6 +117,27 @@ def test_minimax_model_config_exposes_current_metadata(assert config["pricing_usd_per_million_tokens"] == pricing+def test_minimax_current_catalog_and_legacy_resolution():+ assert list(MODEL_CONFIG["MINIMAX_MODELS"].values()) == [+ "MiniMax-M3.1-Flash",+ "MiniMax-M3",+ ]+ assert get_model_config("MiniMax-M2.7")["model"] == "MiniMax-M2.7"+ flash = get_model_config("MiniMax-M3.1-Flash")+ assert flash["max_output_tokens"] == 524_288+ assert flash["reasoning_effort"] == ["low", "medium", "high", "xhigh", "max"]+ assert flash["default_reasoning_effort"] == "max"+ assert get_model_config("MiniMax-M3")[+ "long_context_pricing_usd_per_million_tokens"+ ] == {+ "input_range": ">512k",+ "input": 0.6,+ "output": 2.4,+ "cache_read": 0.12,+ "cache_write": None,+ }++def test_minimax_model_config_rejects_unknown_region(monkeypatch):monkeypatch.setenv("MINIMAX_API_REGION", "unknown")monkeypatch.delenv("MINIMAX_API_BASE", raising=False)diff --git a/tests/test_minimax_client.py b/tests/test_minimax_client.pynew file mode 100644index 0000000..3b0670b--- /dev/null+++ b/tests/test_minimax_client.py@@ -0,0 +1,246 @@+"""Offline SDK transport coverage; run with the frozen eval dependencies."""++import asyncio+import json+import sys+import types+from pathlib import Path++import pytest++httpx = pytest.importorskip("httpx")+openai = pytest.importorskip("openai")++_LIB = Path(__file__).parents[1] / "eval" / "lib"+if "lib" not in sys.modules:+ _pkg = types.ModuleType("lib")+ _pkg.__path__ = [str(_LIB)]+ sys.modules["lib"] = _pkg++from lib.llm import LLMClient, build_messages, build_react_messages+from lib.model_config import get_model_config+from lib.retrieval import RetrievalResult+++def captured_requests(monkeypatch):+ requests = []+ sdk_client = openai.AsyncOpenAI++ def respond(request):+ requests.append(request)+ return httpx.Response(+ 200,+ json={+ "id": "offline-completion",+ "object": "chat.completion",+ "created": 0,+ "model": json.loads(request.content)["model"],+ "choices": [+ {+ "index": 0,+ "finish_reason": "stop",+ "message": {+ "role": "assistant",+ "content": "<search>next evidence</search>",+ "reasoning_content": "Keep this reasoning for the next turn.",+ },+ }+ ],+ "usage": {+ "prompt_tokens": 10,+ "completion_tokens": 5,+ "total_tokens": 15,+ },+ },+ )++ def client(**kwargs):+ return sdk_client(+ **kwargs,+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(respond)),+ )++ monkeypatch.setattr(openai, "AsyncOpenAI", client)+ monkeypatch.setenv("MINIMAX_API_KEY", "offline-test-key")+ monkeypatch.setenv("API_KEY", "offline-fallback-key")+ monkeypatch.delenv("MINIMAX_API_BASE", raising=False)+ monkeypatch.delenv("MINIMAX_ANTHROPIC_API_BASE", raising=False)+ return requests+++def reader(model, **kwargs):+ config = get_model_config(model)+ return LLMClient(+ **{key: config[key] for key in ("model", "api_base", "api_key")},+ **kwargs,+ )+++async def generate_and_close(client, messages):+ try:+ return await client.generate(messages)+ finally:+ await client.client.close()+++ "region,host",+ [+ ("global_en", "api.minimax.io"),+ ("cn_zh", "api.minimaxi.com"),+ ],+)+ "model",+ [+ "MiniMax-M3.1-Flash",+ "MiniMax/MiniMax-M3.1-Flash",+ "MiniMax-M3",+ "MiniMax-M2.7",+ ],+)+def test_minimax_serializes_regional_requests(+ monkeypatch, captured_requests, region, host, model+):+ monkeypatch.setenv("MINIMAX_API_REGION", region)+ messages = build_messages(+ "Read the evidence", RetrievalResult(base64_image="aW1hZ2U=")+ )+ messages.extend(+ [+ {+ "role": "assistant",+ "content": "<think>Existing reasoning</think>",+ "reasoning_content": "Existing separate reasoning",+ "tool_calls": [+ {+ "id": "call_search",+ "type": "function",+ "function": {+ "name": "search",+ "arguments": '{"query":"evidence"}',+ },+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_search",+ "content": "Evidence found",+ },+ {"role": "user", "content": "Answer now"},+ ]+ )+ text, usage = asyncio.run(generate_and_close(reader(model), messages))+ request = captured_requests[0]+ payload = json.loads(request.content)+ assert request.url == f"https://{host}/v1/chat/completions"+ assert request.headers["authorization"] == "Bearer offline-test-key"+ assert payload["model"] == model.rsplit("/", 1)[-1]+ assert payload["messages"] == messages+ assert payload["max_tokens"] == 16384+ assert (+ not {+ "thinking",+ "reasoning_effort",+ "service_tier",+ "reasoning_split",+ "chat_template_kwargs",+ }+ & payload.keys()+ )+ assert text == "<search>next evidence</search>"+ assert usage["total_tokens"] == 15+++ "model,thinking,expected",+ [+ ("MiniMax-M3.1-Flash", True, "adaptive"),+ ("MiniMax-M3", True, "adaptive"),+ ("MiniMax-M3", False, "disabled"),+ ],+)+def test_minimax_explicit_thinking(captured_requests, model, thinking, expected):+ asyncio.run(+ generate_and_close(+ reader(model, enable_thinking=thinking),+ [{"role": "user", "content": "Hello"}],+ )+ )+ payload = json.loads(captured_requests[0].content)+ assert payload["thinking"] == {"type": expected}+ assert "chat_template_kwargs" not in payload+++def test_flash_rejects_disabled_thinking_before_request(captured_requests):+ with pytest.raises(ValueError, match="requires adaptive thinking"):+ reader("MiniMax-M3.1-Flash", enable_thinking=False)+ assert captured_requests == []+++ "model,base,env_name",+ [+ ("MiniMax-M3.1-Flash", "https://gateway.example/custom/v1", "MINIMAX_API_BASE"),+ ("MiniMax-M2.7-highspeed", "http://localhost:9000/v1", "API_BASE"),+ ("custom-reader", "http://localhost:9000/v1", "API_BASE"),+ ],+)+def test_explicit_custom_routes_keep_existing_parameters(+ monkeypatch, captured_requests, model, base, env_name+):+ monkeypatch.setenv(env_name, base)+ asyncio.run(+ generate_and_close(+ reader(model, enable_thinking=False), [{"role": "user", "content": "Hello"}]+ )+ )+ assert captured_requests[0].url == f"{base}/chat/completions"+ payload = json.loads(captured_requests[0].content)+ assert payload["model"] == model+ assert payload["chat_template_kwargs"] == {"enable_thinking": False}+ assert "thinking" not in payload+++def test_flash_react_replays_complete_assistant_message(captured_requests):+ async def run():+ client = reader("MiniMax-M3.1-Flash")+ evidence = RetrievalResult(images=[("a" * 300, 1.0)])+ try:+ text, usage = await client.generate(+ build_react_messages(+ "Question", [evidence], [], encode_image_fn=lambda _: "unused"+ )+ )+ assert text == "<search>next evidence</search>"+ # Mirrors run_bench: read without mutating, and the recorded+ # token dict must not carry the conversation message.+ history = usage.get("_assistant_message", text)+ assert [k for k in usage if k.startswith("_")] == ["_assistant_message"]+ assert {k for k in usage if not k.startswith("_")} <= {+ "prompt_tokens",+ "completion_tokens",+ "total_tokens",+ }+ await client.generate(+ build_react_messages(+ "Question",+ [evidence, evidence],+ [history],+ encode_image_fn=lambda _: "unused",+ )+ )+ finally:+ await client.client.close()++ asyncio.run(run())+ payload = json.loads(captured_requests[1].content)+ assert payload["messages"][2] == {+ "role": "assistant",+ "content": "<search>next evidence</search>",+ "reasoning_content": "Keep this reasoning for the next turn.",+ }+ assert payload["messages"][1]["content"][1]["type"] == "image_url"+ assert payload["messages"][3]["content"][1]["type"] == "image_url"