"""Shared OpenAI-compatible client for the LLM method families. Every LLM-family method (``methods/llm.py``, ``methods/llm_ts_reason.py``, ``methods/llm_finetune.py``) talks to a vLLM-served model via the OpenAI HTTP API. This module owns the client lifecycle and the batch-fan-out helper so the per-task code paths can rely on a single shared protocol:: text: str = engine.chat_complete(messages, max_tokens=256, temperature=0.0) texts: list[str] = engine.chat_complete_batch( [messages_a, messages_b, ...], max_tokens=256, temperature=0.0, ) Why a shared module ------------------- Before this refactor the three LLM-family files used three different engine protocols (``vllm.LLM.generate``, ``engine.answer``, ``engine.generate``). Centralising the protocol on the OpenAI-compatible HTTP client lets vLLM serve the model out-of-process behind ``vllm serve ...`` and removes the in-process Python SDK dependency from the runner. Canonical vLLM serve commands (one terminal per model) ------------------------------------------------------ The ``model_id`` strings below match the defaults in ``methods/_config.py`` (``LlamaScoutConfig`` / ``Gemma4Config`` / ``Exaone45Config`` / ``Qwen35Config`` and the ``llm_ts_reason`` configs). Any out-of-band fine-tune is served as a separate ``model`` id on the LoRA-aware vLLM endpoint:: # Llama-4 Scout 109B-MoE (FP8) — TP=4 vllm serve meta-llama/Llama-4-Scout-17B-16E-Instruct \\ --tensor-parallel-size 4 --gpu-memory-utilization 0.9 \\ --port 8001 --quantization fp8 # Gemma-4 31B (FP8) — TP=2 vllm serve google/gemma-4-31B-it --tensor-parallel-size 2 \\ --port 8002 --quantization fp8 # EXAONE-4.5 33B (FP8) — TP=2 vllm serve LGAI-EXAONE/EXAONE-4.5-33B-FP8 --tensor-parallel-size 2 \\ --port 8003 --quantization fp8 # Qwen-3.5 27B (FP8) — TP=1 vllm serve Qwen/Qwen3.5-27B-FP8 --tensor-parallel-size 1 \\ --port 8004 --quantization fp8 # ChatTime-1-7B-Chat vllm serve ChengsenWang/ChatTime-1-7B-Chat --tensor-parallel-size 1 \\ --port 8005 # ITFormer-ICML25 vllm serve Pandalin98/ITFormer-ICML25 --tensor-parallel-size 1 \\ --port 8006 # Time-MQA (LoRA over Qwen2.5-7B) vllm serve Qwen/Qwen2.5-7B-Instruct --tensor-parallel-size 1 \\ --port 8007 --enable-lora \\ --lora-modules time_mqa=Time-MQA/Qwen-2.5-7B # LLMFineTuned (LoRA-served on top of one of the panel base models) vllm serve --enable-lora \\ --lora-modules llm_finetuned= \\ --port 8008 """ from __future__ import annotations import logging from concurrent.futures import ThreadPoolExecutor from typing import Any, Sequence logger = logging.getLogger(__name__) # ── Real engine: OpenAI Python SDK against a vLLM HTTP endpoint ────────── class OpenAIChatEngine: """Thin wrapper around the OpenAI Python SDK targeting a vLLM endpoint. Construction:: engine = OpenAIChatEngine( base_url="http://localhost:8001/v1", api_key="EMPTY", model_id="meta-llama/Llama-4-Scout-17B-16E-Instruct", n_workers=8, request_timeout_sec=300.0, ) The OpenAI SDK is sync-per-call; ``chat_complete_batch`` fans out N independent requests over a thread pool (the standard pattern for parallelising HTTP I/O without requiring an async event loop). """ def __init__( self, *, base_url: str, api_key: str = "EMPTY", model_id: str, n_workers: int = 8, request_timeout_sec: float = 300.0, ) -> None: import os, json from openai import OpenAI self.base_url = base_url self.model_id = model_id self.n_workers = int(n_workers) self.request_timeout_sec = float(request_timeout_sec) self._client = OpenAI( base_url=base_url, api_key=api_key, timeout=request_timeout_sec, ) # Optional OpenRouter provider routing via env var. # MACROLENS_LLM_EXTRA_BODY = JSON dict, e.g. # '{"provider": {"order": ["DeepInfra"]}}' # Forwarded as extra_body to chat.completions.create. eb = os.environ.get("MACROLENS_LLM_EXTRA_BODY", "").strip() self._extra_body: dict | None = None if eb: try: self._extra_body = json.loads(eb) except json.JSONDecodeError: self._extra_body = None def chat_complete( self, messages: list[dict[str, str]], *, max_tokens: int = 256, temperature: float = 0.0, top_p: float = 1.0, ) -> str: """Single chat completion. Returns the assistant message text.""" kwargs: dict = dict( model=self.model_id, messages=messages, max_tokens=max_tokens, temperature=temperature, top_p=top_p, ) if self._extra_body: kwargs["extra_body"] = self._extra_body resp = self._client.chat.completions.create(**kwargs) return resp.choices[0].message.content or "" def chat_complete_batch( self, batched_messages: Sequence[list[dict[str, str]]], *, max_tokens: int = 256, temperature: float = 0.0, top_p: float = 1.0, ) -> list[str]: """Fan out N chat completions over a thread pool. Order preserved. Per-request exceptions (HTTP errors, JSON-decode failures from a provider returning HTML error pages, connection resets) are caught here so one bad response cannot kill an entire batch of 1,000 predictions: the failed slot returns the empty string and the downstream parser substitutes NaN, which the eval-side fillna(0) rule scores as the predict-zero penalty. """ if not batched_messages: return [] def _safe(msgs: list[dict[str, str]]) -> str: try: return self.chat_complete( msgs, max_tokens=max_tokens, temperature=temperature, top_p=top_p, ) except Exception as e: logger.warning( "chat_complete failed for one prompt: %s; emitting empty " "string (downstream parser will yield NaN).", type(e).__name__, ) return "" with ThreadPoolExecutor(max_workers=self.n_workers) as ex: futs = [ex.submit(_safe, msgs) for msgs in batched_messages] return [f.result() for f in futs] # ── Dry-run engine for CPU-only smoke tests ────────────────────────────── class DryRunEngine: """Deterministic CPU-only stand-in for unit-test / dry-run paths. ``chat_complete`` returns a single parseable fake response that matches every parser path the LLM-family methods use simultaneously (number, JSON object, JSON list). The horizon is parameterised so T1 JSON-array predictions tile to the right width. """ def __init__(self, horizon: int = 21) -> None: self.horizon = int(horizon) self.model_id = "dry-run" def chat_complete( self, messages: list[dict[str, str]], *, max_tokens: int = 256, temperature: float = 0.0, top_p: float = 1.0, ) -> str: # Inspect the user prompt to honour task-specific horizon hints # (e.g. T1 prompts that say "JSON array of N floats"). If the # message lists do not surface a hint, fall back to ``self.horizon``. horizon = self.horizon try: text = " ".join( str(m.get("content", "")) for m in (messages or []) ).lower() except Exception: text = "" import re as _re m = _re.search(r"json array of (\d+) floats", text) if m: try: horizon = int(m.group(1)) except ValueError: pass list_str = "[" + ", ".join(["1.0"] * horizon) + "]" return ( f'{{"value": 1.0, "rent": 2000.0, "price": 500000.0, ' f'"Revenues": 1000000, "NetIncomeLoss": 100000}} ' f"forecast=1.0 return=0.0 trajectory={list_str}" ) def chat_complete_batch( self, batched_messages: Sequence[list[dict[str, str]]], *, max_tokens: int = 256, temperature: float = 0.0, top_p: float = 1.0, ) -> list[str]: return [ self.chat_complete( msgs, max_tokens=max_tokens, temperature=temperature, top_p=top_p, ) for msgs in batched_messages ] __all__ = ["OpenAIChatEngine", "DryRunEngine"]