Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
fix: update MiniMax model metadata and endpoints (#1103)
Octopuse5f8f2bf008c
diff --git a/README.md b/README.mdindex 491f5c13..989f2674 100644--- a/README.md+++ b/README.md@@ -155,7 +155,7 @@ There are other pipelines that can be used to extract information from multipleFor each of these graphs there is the multi version. It allows to make calls of the LLM in parallel.-It is possible to use different LLM through APIs, such as **OpenAI**, **Groq**, **Azure**, **Gemini**, **MiniMax** and more, or local models using **Ollama**.+It is possible to use different LLM through APIs, such as **OpenAI**, **Groq**, **Azure**, **Gemini**, **[MiniMax](docs/minimax.md)** and more, or local models using **Ollama**.Remember to have [Ollama](https://ollama.com/) installed and download the models using the **ollama pull** command, if you want to use local models.diff --git a/scrapegraphai/helpers/models_tokens.py b/scrapegraphai/helpers/models_tokens.pyindex d0234c17..b5aef2f9 100644--- a/scrapegraphai/helpers/models_tokens.py+++ b/scrapegraphai/helpers/models_tokens.py@@ -412,8 +412,8 @@ models_tokens = {"grok-beta": 128000,},"minimax": {- "MiniMax-M3": 524288,- "MiniMax-M2.7": 204000,- "MiniMax-M2.7-highspeed": 204000,+ "MiniMax-M3": 1000000,+ "MiniMax-M2.7": 204800,+ "MiniMax-M2.7-highspeed": 204800,},}diff --git a/scrapegraphai/models/minimax.py b/scrapegraphai/models/minimax.pyindex ae08d0c6..420cc420 100644--- a/scrapegraphai/models/minimax.py+++ b/scrapegraphai/models/minimax.py@@ -5,6 +5,9 @@ MiniMax Modulefrom langchain_openai import ChatOpenAI+DEFAULT_MINIMAX_OPENAI_BASE_URL = "https://api.minimax.io/v1"++class MiniMax(ChatOpenAI):"""A wrapper for the ChatOpenAI class (MiniMax uses an OpenAI-compatible API) that@@ -18,6 +21,7 @@ class MiniMax(ChatOpenAI):def __init__(self, **llm_config):if "api_key" in llm_config:llm_config["openai_api_key"] = llm_config.pop("api_key")- llm_config["openai_api_base"] = "https://api.minimax.io/v1"+ if "base_url" not in llm_config and "openai_api_base" not in llm_config:+ llm_config["openai_api_base"] = DEFAULT_MINIMAX_OPENAI_BASE_URLsuper().__init__(**llm_config)diff --git a/scrapegraphai/utils/custom_callback.py b/scrapegraphai/utils/custom_callback.pyindex 6cf6aeab..c2a881a6 100644--- a/scrapegraphai/utils/custom_callback.py+++ b/scrapegraphai/utils/custom_callback.py@@ -15,11 +15,19 @@ from langchain_core.messages import AIMessagefrom langchain_core.outputs import ChatGeneration, LLMResultfrom langchain_core.tracers.context import register_configure_hook-from .model_costs import MODEL_COST_PER_1K_TOKENS_INPUT, MODEL_COST_PER_1K_TOKENS_OUTPUT+from .model_costs import (+ MODEL_COST_PER_1K_TOKENS_INPUT,+ MODEL_COST_TIERS_PER_1K_TOKENS,+ get_model_cost_per_1k_tokens,+)def get_token_cost_for_model(- model_name: str, num_tokens: int, is_completion: bool = False+ model_name: str,+ num_tokens: int,+ is_completion: bool = False,+ input_tokens: Optional[int] = None,+ service_tier: str = "standard",) -> float:"""Get the cost in USD for a given model and number of tokens.@@ -29,15 +37,30 @@ def get_token_cost_for_model(num_tokens: Number of tokens.is_completion: Whether the model is used for completion or not.Defaults to False.+ input_tokens: Number of input tokens used to select a pricing tier.+ service_tier: Provider service tier. Defaults to standard.Returns:Cost in USD."""- if model_name not in MODEL_COST_PER_1K_TOKENS_INPUT:+ if (+ model_name not in MODEL_COST_PER_1K_TOKENS_INPUT+ and model_name not in MODEL_COST_TIERS_PER_1K_TOKENS+ ):return 0.0- if is_completion:- return MODEL_COST_PER_1K_TOKENS_OUTPUT[model_name] * (num_tokens / 1000)- return MODEL_COST_PER_1K_TOKENS_INPUT[model_name] * (num_tokens / 1000)+ if input_tokens is None:+ if is_completion and model_name in MODEL_COST_TIERS_PER_1K_TOKENS:+ raise ValueError(+ "input_tokens is required for completion costs with tiered pricing"+ )+ input_tokens = num_tokens+ rate = get_model_cost_per_1k_tokens(+ model_name,+ input_tokens,+ is_completion=is_completion,+ service_tier=service_tier,+ )+ return rate * (num_tokens / 1000)class CustomCallbackHandler(BaseCallbackHandler):@@ -49,10 +72,11 @@ class CustomCallbackHandler(BaseCallbackHandler):successful_requests: int = 0total_cost: float = 0.0- def __init__(self, llm_model_name: str) -> None:+ def __init__(self, llm_model_name: str, service_tier: str = "standard") -> None:super().__init__()self._lock = threading.Lock()self.model_name = llm_model_name if llm_model_name else "unknown"+ self.service_tier = service_tierdef __repr__(self) -> str:return (@@ -114,11 +138,23 @@ class CustomCallbackHandler(BaseCallbackHandler):token_usage = response.llm_output["token_usage"]completion_tokens = token_usage.get("completion_tokens", 0)prompt_tokens = token_usage.get("prompt_tokens", 0)- if self.model_name in MODEL_COST_PER_1K_TOKENS_INPUT:+ if (+ self.model_name in MODEL_COST_PER_1K_TOKENS_INPUT+ or self.model_name in MODEL_COST_TIERS_PER_1K_TOKENS+ ):completion_cost = get_token_cost_for_model(- self.model_name, completion_tokens, is_completion=True+ self.model_name,+ completion_tokens,+ is_completion=True,+ input_tokens=prompt_tokens,+ service_tier=self.service_tier,+ )+ prompt_cost = get_token_cost_for_model(+ self.model_name,+ prompt_tokens,+ input_tokens=prompt_tokens,+ service_tier=self.service_tier,)- prompt_cost = get_token_cost_for_model(self.model_name, prompt_tokens)else:completion_cost = 0prompt_cost = 0@@ -147,11 +183,11 @@ register_configure_hook(custom_callback, True)@contextmanager-def get_custom_callback(llm_model_name: str):+def get_custom_callback(llm_model_name: str, service_tier: str = "standard"):"""Function to get custom callback for LLM token usage statistics."""- cb = CustomCallbackHandler(llm_model_name)+ cb = CustomCallbackHandler(llm_model_name, service_tier=service_tier)custom_callback.set(cb)yield cbcustom_callback.set(None)diff --git a/scrapegraphai/utils/llm_callback_manager.py b/scrapegraphai/utils/llm_callback_manager.pyindex 28a11165..35a2da9d 100644--- a/scrapegraphai/utils/llm_callback_manager.py+++ b/scrapegraphai/utils/llm_callback_manager.py@@ -47,7 +47,15 @@ class CustomLLMCallbackManager:"""if CustomLLMCallbackManager._lock.acquire(blocking=False):try:- if isinstance(llm_model, ChatOpenAI) or isinstance(+ from ..models.minimax import MiniMax++ if isinstance(llm_model, MiniMax):+ service_tier = llm_model.service_tier or "standard"+ with get_custom_callback(+ llm_model_name, service_tier=service_tier+ ) as cb:+ yield cb+ elif isinstance(llm_model, ChatOpenAI) or isinstance(llm_model, AzureChatOpenAI):with get_openai_callback() as cb:diff --git a/scrapegraphai/utils/model_costs.py b/scrapegraphai/utils/model_costs.pyindex 0b8fb9ec..861d9536 100644--- a/scrapegraphai/utils/model_costs.py+++ b/scrapegraphai/utils/model_costs.py@@ -50,6 +50,7 @@ MODEL_COST_PER_1K_TOKENS_INPUT = {"amazon.titan-text-express-v1": 0.0002,"amazon.titan-text-lite-v1": 0.00015,"amazon.titan-text-premier-v1:0": 0.0005,+ "MiniMax-M2.7": 0.0003,}"""@@ -102,4 +103,84 @@ MODEL_COST_PER_1K_TOKENS_OUTPUT = {"amazon.titan-text-express-v1": 0.0006,"amazon.titan-text-lite-v1": 0.0002,"amazon.titan-text-premier-v1:0": 0.0015,+ "MiniMax-M2.7": 0.0012,}+++MODEL_CACHE_COST_PER_1K_TOKENS = {+ "MiniMax-M2.7": {"read": 0.00006, "write": 0.000375},+}+++MODEL_COST_TIERS_PER_1K_TOKENS = {+ "MiniMax-M3": {+ "standard": (+ {+ "input_tokens_lte": 512000,+ "input": 0.0003,+ "output": 0.0012,+ "cache_read": 0.00006,+ "cache_write": None,+ },+ {+ "input_tokens_gt": 512000,+ "input": 0.0006,+ "output": 0.0024,+ "cache_read": 0.00012,+ "cache_write": None,+ },+ ),+ "priority": (+ {+ "input_tokens_lte": 512000,+ "input": 0.00045,+ "output": 0.0018,+ "cache_read": 0.00009,+ "cache_write": None,+ },+ {+ "input_tokens_gt": 512000,+ "input": 0.0009,+ "output": 0.0036,+ "cache_read": 0.00018,+ "cache_write": None,+ },+ ),+ }+}+++def get_model_cost_per_1k_tokens(+ model_name: str,+ input_tokens: int,+ is_completion: bool = False,+ service_tier: str = "standard",+) -> float:+ """Return the applicable input or output rate for a model."""+ if input_tokens < 0:+ raise ValueError("input_tokens must not be negative")++ if model_name in MODEL_COST_TIERS_PER_1K_TOKENS:+ try:+ pricing_tiers = MODEL_COST_TIERS_PER_1K_TOKENS[model_name][service_tier]+ except KeyError as exc:+ raise ValueError(+ f"Unsupported service tier {service_tier!r} for {model_name}"+ ) from exc++ rate_key = "output" if is_completion else "input"+ for pricing in pricing_tiers:+ upper_bound = pricing.get("input_tokens_lte")+ lower_bound = pricing.get("input_tokens_gt")+ if upper_bound is not None and input_tokens <= upper_bound:+ return float(pricing[rate_key])+ if lower_bound is not None and input_tokens > lower_bound:+ return float(pricing[rate_key])+ raise ValueError(f"No pricing tier matches {input_tokens} input tokens")++ costs = (+ MODEL_COST_PER_1K_TOKENS_OUTPUT+ if is_completion+ else MODEL_COST_PER_1K_TOKENS_INPUT+ )+ return costs[model_name]diff --git a/tests/test_minimax_models.py b/tests/test_minimax_models.pyindex ec41d5e9..637847eb 100644--- a/tests/test_minimax_models.py+++ b/tests/test_minimax_models.py@@ -3,7 +3,9 @@import importlib.utilimport osimport sys+import types+import httpximport pytest@@ -25,6 +27,65 @@ def models_tokens():return module.models_tokens[email protected](scope="module")+def model_costs():+ """Import model_costs directly to avoid triggering the full package init."""+ spec = importlib.util.spec_from_file_location(+ "model_costs",+ os.path.join(+ os.path.dirname(__file__),+ "..",+ "scrapegraphai",+ "utils",+ "model_costs.py",+ ),+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++[email protected](scope="module")+def minimax_module():+ """Import the MiniMax adapter without loading the package initializer."""+ spec = importlib.util.spec_from_file_location(+ "minimax",+ os.path.join(+ os.path.dirname(__file__),+ "..",+ "scrapegraphai",+ "models",+ "minimax.py",+ ),+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++[email protected](scope="module")+def custom_callback_module(model_costs):+ """Import custom_callback with its local model_costs dependency."""+ package_name = "_minimax_test_utils"+ package = types.ModuleType(package_name)+ package.__path__ = []+ sys.modules[package_name] = package+ sys.modules[f"{package_name}.model_costs"] = model_costs+ spec = importlib.util.spec_from_file_location(+ f"{package_name}.custom_callback",+ os.path.join(+ os.path.dirname(__file__),+ "..",+ "scrapegraphai",+ "utils",+ "custom_callback.py",+ ),+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++def test_minimax_m3_in_model_list(models_tokens):"""MiniMax-M3 should be in the model list."""minimax_models = models_tokens["minimax"]@@ -57,6 +118,157 @@ def test_minimax_deprecated_models_removed(models_tokens):def test_minimax_token_limits(models_tokens):"""MiniMax model token limits should match upstream documentation."""minimax_models = models_tokens["minimax"]- assert minimax_models["MiniMax-M3"] == 524288- assert minimax_models["MiniMax-M2.7"] == 204000- assert minimax_models["MiniMax-M2.7-highspeed"] == 204000+ assert minimax_models["MiniMax-M3"] == 1000000+ assert minimax_models["MiniMax-M2.7"] == 204800+ assert minimax_models["MiniMax-M2.7-highspeed"] == 204800+++def test_minimax_m27_costs(model_costs):+ """MiniMax-M2.7 should retain all published token rates."""+ assert model_costs.MODEL_COST_PER_1K_TOKENS_INPUT["MiniMax-M2.7"] == 0.0003+ assert model_costs.MODEL_COST_PER_1K_TOKENS_OUTPUT["MiniMax-M2.7"] == 0.0012+ assert model_costs.MODEL_CACHE_COST_PER_1K_TOKENS["MiniMax-M2.7"] == {+ "read": 0.00006,+ "write": 0.000375,+ }+++ (+ "service_tier",+ "input_tokens",+ "input_rate",+ "output_rate",+ "cache_read_rate",+ ),+ [+ ("standard", 512000, 0.0003, 0.0012, 0.00006),+ ("standard", 512001, 0.0006, 0.0024, 0.00012),+ ("priority", 512000, 0.00045, 0.0018, 0.00009),+ ("priority", 512001, 0.0009, 0.0036, 0.00018),+ ],+)+def test_minimax_m3_tiered_costs(+ model_costs,+ service_tier,+ input_tokens,+ input_rate,+ output_rate,+ cache_read_rate,+):+ """MiniMax-M3 pricing should preserve service and context tiers."""+ assert (+ model_costs.get_model_cost_per_1k_tokens(+ "MiniMax-M3", input_tokens, service_tier=service_tier+ )+ == input_rate+ )+ assert (+ model_costs.get_model_cost_per_1k_tokens(+ "MiniMax-M3",+ input_tokens,+ is_completion=True,+ service_tier=service_tier,+ )+ == output_rate+ )+ tier_index = 0 if input_tokens <= 512000 else 1+ pricing = model_costs.MODEL_COST_TIERS_PER_1K_TOKENS["MiniMax-M3"][service_tier][+ tier_index+ ]+ assert pricing["cache_read"] == cache_read_rate+ assert pricing["cache_write"] is None+++def test_minimax_m3_callback_uses_input_token_tier(custom_callback_module):+ """The callback should apply one input tier to both token directions."""+ response = types.SimpleNamespace(+ generations=[[]],+ llm_output={+ "token_usage": {+ "prompt_tokens": 512001,+ "completion_tokens": 1000,+ "total_tokens": 513001,+ }+ },+ )+ callback = custom_callback_module.CustomCallbackHandler("MiniMax-M3")++ callback.on_llm_end(response)++ expected_input_cost = 0.0006 * (512001 / 1000)+ expected_output_cost = 0.0024+ assert callback.total_cost == pytest.approx(+ expected_input_cost + expected_output_cost+ )+++def test_minimax_callback_manager_uses_tiered_costs():+ """MiniMax should use its tier-aware callback before the OpenAI fallback."""+ from scrapegraphai.models.minimax import MiniMax+ from scrapegraphai.utils.custom_callback import CustomCallbackHandler+ from scrapegraphai.utils.llm_callback_manager import CustomLLMCallbackManager++ model = MiniMax(+ model="MiniMax-M3",+ api_key="test-key",+ service_tier="priority",+ )++ with CustomLLMCallbackManager().exclusive_get_callback(+ model, "MiniMax-M3"+ ) as callback:+ assert isinstance(callback, CustomCallbackHandler)+ assert callback.service_tier == "priority"+++ "base_url",+ ["https://api.minimax.io/v1", "https://api.minimaxi.com/v1"],+)+def test_minimax_openai_request_path(minimax_module, base_url):+ """The adapter should preserve either regional OpenAI-compatible base URL."""+ request_urls = []++ def handle_request(request):+ request_urls.append(str(request.url))+ return httpx.Response(+ 200,+ request=request,+ json={+ "id": "chatcmpl-test",+ "object": "chat.completion",+ "created": 0,+ "model": "MiniMax-M3",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "Done."},+ "finish_reason": "stop",+ }+ ],+ "usage": {+ "prompt_tokens": 1,+ "completion_tokens": 1,+ "total_tokens": 2,+ },+ },+ )++ http_client = httpx.Client(transport=httpx.MockTransport(handle_request))+ model = minimax_module.MiniMax(+ model="MiniMax-M3",+ api_key="test-key",+ base_url=base_url,+ http_client=http_client,+ )++ model.invoke("Test")++ assert request_urls == [f"{base_url}/chat/completions"]+++def test_minimax_defaults_to_global_openai_endpoint(minimax_module):+ """The adapter should keep the global OpenAI-compatible endpoint as default."""+ model = minimax_module.MiniMax(model="MiniMax-M3", api_key="test-key")+ assert str(model.openai_api_base).rstrip("/") == "https://api.minimax.io/v1"