llm_call.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #!/usr/bin/env python3
  2. """
  3. Multi-protocol LLM caller.
  4. Reads provider config from the active MiniMax Code data directory and calls LLM APIs using the
  5. correct protocol (Messages, OpenAI Chat Completions, or Gemini
  6. generateContent) based on the provider's `npm` field.
  7. Dependencies: httpx, pyyaml
  8. pip install httpx pyyaml
  9. """
  10. from __future__ import annotations
  11. import argparse
  12. import json
  13. import os
  14. import sys
  15. from abc import ABC, abstractmethod
  16. from pathlib import Path
  17. from typing import Any
  18. import httpx
  19. import yaml
  20. # ---------------------------------------------------------------------------
  21. # Config loading
  22. # ---------------------------------------------------------------------------
  23. def _default_data_dir() -> Path:
  24. return Path(
  25. os.environ.get('__MAVIS_PARENT_DATA_DIR')
  26. or os.environ.get('MINIMAX_DATA_DIR')
  27. or str(Path.home() / ".minimax")
  28. )
  29. DEFAULT_CONFIG_PATH = _default_data_dir() / "config.yaml"
  30. def load_config(config_path: str | Path | None = None) -> dict[str, Any]:
  31. path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH
  32. if not path.exists():
  33. print(f"Error: config file not found at {path}", file=sys.stderr)
  34. sys.exit(1)
  35. with open(path) as f:
  36. return yaml.safe_load(f)
  37. # ---------------------------------------------------------------------------
  38. # Protocol implementations
  39. # ---------------------------------------------------------------------------
  40. NPM_TO_PROTOCOL: dict[str, str] = {
  41. "@ai-sdk/anthropic": "anthropic",
  42. "@ai-sdk/openai": "chat-completions",
  43. "@ai-sdk/google": "gemini",
  44. }
  45. class Protocol(ABC):
  46. """Base class for LLM API protocols."""
  47. @abstractmethod
  48. def build_request(
  49. self,
  50. base_url: str,
  51. model_id: str,
  52. messages: list[dict[str, str]],
  53. *,
  54. max_tokens: int = 4096,
  55. temperature: float | None = None,
  56. stream: bool = False,
  57. extra_headers: dict[str, str] | None = None,
  58. model_options: dict[str, Any] | None = None,
  59. ) -> tuple[str, dict[str, str], dict[str, Any]]:
  60. """Return (url, headers, body)."""
  61. @abstractmethod
  62. def extract_text(self, data: dict[str, Any]) -> str:
  63. """Extract the assistant's text from a non-streaming response."""
  64. @abstractmethod
  65. def extract_stream_delta(self, data: dict[str, Any]) -> str | None:
  66. """Extract incremental text from a streaming SSE data chunk."""
  67. class MessagesProtocol(Protocol):
  68. def build_request(self, base_url, model_id, messages, *, max_tokens=4096,
  69. temperature=None, stream=False, extra_headers=None,
  70. model_options=None):
  71. url = f"{base_url.rstrip('/')}/messages"
  72. headers = {
  73. "Content-Type": "application/json",
  74. }
  75. if extra_headers:
  76. headers.update(extra_headers)
  77. # Messages API requires system as a top-level parameter,
  78. # not as a message with role "system".
  79. system_parts: list[str] = []
  80. filtered_messages: list[dict[str, str]] = []
  81. for msg in messages:
  82. if msg["role"] == "system":
  83. system_parts.append(msg["content"])
  84. else:
  85. filtered_messages.append(msg)
  86. body: dict[str, Any] = {
  87. "model": model_id,
  88. "max_tokens": max_tokens,
  89. "messages": filtered_messages,
  90. }
  91. if system_parts:
  92. body["system"] = "\n\n".join(system_parts)
  93. if temperature is not None:
  94. body["temperature"] = temperature
  95. if stream:
  96. body["stream"] = True
  97. return url, headers, body
  98. def extract_text(self, data):
  99. for block in data.get("content", []):
  100. if block.get("type") == "text":
  101. return block["text"]
  102. return ""
  103. def extract_stream_delta(self, data):
  104. evt_type = data.get("type", "")
  105. if evt_type == "content_block_delta":
  106. delta = data.get("delta", {})
  107. if delta.get("type") == "text_delta":
  108. return delta.get("text", "")
  109. return None
  110. class ChatCompletionsProtocol(Protocol):
  111. def build_request(self, base_url, model_id, messages, *, max_tokens=4096,
  112. temperature=None, stream=False, extra_headers=None,
  113. model_options=None):
  114. url = f"{base_url.rstrip('/')}/chat/completions"
  115. headers = {"Content-Type": "application/json"}
  116. if extra_headers:
  117. headers.update(extra_headers)
  118. body: dict[str, Any] = {
  119. "model": model_id,
  120. "max_tokens": max_tokens,
  121. "messages": messages,
  122. }
  123. if temperature is not None:
  124. body["temperature"] = temperature
  125. if stream:
  126. body["stream"] = True
  127. # Forward model-level options (e.g. reasoning_effort, store)
  128. if model_options:
  129. for key in ("store", "effort", "reasoningSummary"):
  130. if key in model_options:
  131. body[key] = model_options[key]
  132. return url, headers, body
  133. def extract_text(self, data):
  134. choices = data.get("choices", [])
  135. if choices:
  136. return choices[0].get("message", {}).get("content", "")
  137. return ""
  138. def extract_stream_delta(self, data):
  139. choices = data.get("choices", [])
  140. if choices:
  141. delta = choices[0].get("delta", {})
  142. return delta.get("content")
  143. return None
  144. class GeminiProtocol(Protocol):
  145. def build_request(self, base_url, model_id, messages, *, max_tokens=4096,
  146. temperature=None, stream=False, extra_headers=None,
  147. model_options=None):
  148. action = "streamGenerateContent" if stream else "generateContent"
  149. url = f"{base_url.rstrip('/')}/models/{model_id}:{action}"
  150. if stream:
  151. url += "?alt=sse"
  152. headers = {"Content-Type": "application/json"}
  153. if extra_headers:
  154. headers.update(extra_headers)
  155. # Convert chat messages to Gemini format
  156. contents: list[dict[str, Any]] = []
  157. system_instruction = None
  158. for msg in messages:
  159. role = msg["role"]
  160. text = msg["content"]
  161. if role == "system":
  162. system_instruction = {"parts": [{"text": text}]}
  163. else:
  164. gemini_role = "model" if role == "assistant" else "user"
  165. contents.append({"role": gemini_role, "parts": [{"text": text}]})
  166. body: dict[str, Any] = {"contents": contents}
  167. if system_instruction:
  168. body["systemInstruction"] = system_instruction
  169. body["generationConfig"] = {"maxOutputTokens": max_tokens}
  170. if temperature is not None:
  171. body["generationConfig"]["temperature"] = temperature
  172. return url, headers, body
  173. def extract_text(self, data):
  174. candidates = data.get("candidates", [])
  175. if candidates:
  176. parts = candidates[0].get("content", {}).get("parts", [])
  177. return "".join(p.get("text", "") for p in parts)
  178. return ""
  179. def extract_stream_delta(self, data):
  180. candidates = data.get("candidates", [])
  181. if candidates:
  182. parts = candidates[0].get("content", {}).get("parts", [])
  183. if parts:
  184. return parts[0].get("text")
  185. return None
  186. PROTOCOLS: dict[str, Protocol] = {
  187. "anthropic": MessagesProtocol(),
  188. "chat-completions": ChatCompletionsProtocol(),
  189. "gemini": GeminiProtocol(),
  190. }
  191. # ---------------------------------------------------------------------------
  192. # LLMCaller
  193. # ---------------------------------------------------------------------------
  194. class LLMCaller:
  195. """High-level interface for calling LLMs from config.yaml."""
  196. def __init__(self, config_path: str | Path | None = None):
  197. self.config = load_config(config_path)
  198. self.providers: dict[str, Any] = self.config.get("provider", {})
  199. self.default_model: str | None = self.config.get("defaultModel")
  200. def list_models(self) -> list[dict[str, str]]:
  201. """Return a flat list of available models with their provider/model ref."""
  202. result = []
  203. for provider_id, pconf in self.providers.items():
  204. models = pconf.get("models", {})
  205. for model_id, mconf in models.items():
  206. ref = f"{provider_id}/{model_id}"
  207. name = mconf.get("name", model_id) if isinstance(mconf, dict) else model_id
  208. is_default = ref == self.default_model
  209. result.append({"ref": ref, "name": name, "default": is_default})
  210. return result
  211. def resolve(self, model_ref: str) -> tuple[str, dict[str, Any], dict[str, Any], str]:
  212. """Resolve 'provider/model' to (protocol_name, provider_config, model_config, model_id)."""
  213. parts = model_ref.split("/", 1)
  214. if len(parts) != 2:
  215. print(f"Error: model must be in 'provider/model' format, got '{model_ref}'",
  216. file=sys.stderr)
  217. sys.exit(1)
  218. provider_id, model_id = parts
  219. pconf = self.providers.get(provider_id)
  220. if not pconf:
  221. print(f"Error: provider '{provider_id}' not found in config.yaml", file=sys.stderr)
  222. sys.exit(1)
  223. mconf = pconf.get("models", {}).get(model_id, {})
  224. npm = pconf.get("npm", "")
  225. protocol_name = NPM_TO_PROTOCOL.get(npm, "chat-completions")
  226. return protocol_name, pconf, mconf, model_id
  227. def call(
  228. self,
  229. model_ref: str,
  230. messages: list[dict[str, str]],
  231. *,
  232. max_tokens: int = 4096,
  233. temperature: float | None = None,
  234. stream: bool = False,
  235. timeout: float = 120.0,
  236. ) -> str:
  237. """Call the specified model and return the response text."""
  238. protocol_name, pconf, mconf, model_id = self.resolve(model_ref)
  239. protocol = PROTOCOLS[protocol_name]
  240. options = pconf.get("options", {})
  241. base_url = options.get("baseURL", "")
  242. api_key = options.get("apiKey", "")
  243. # Merge headers: provider-level + model-level
  244. extra_headers: dict[str, str] = {}
  245. if options.get("headers"):
  246. extra_headers.update(options["headers"])
  247. if isinstance(mconf, dict) and mconf.get("headers"):
  248. extra_headers.update(mconf["headers"])
  249. # Auth header
  250. if api_key:
  251. if protocol_name == "anthropic":
  252. extra_headers["x-api-key"] = api_key
  253. else:
  254. extra_headers["Authorization"] = f"Bearer {api_key}"
  255. model_options = mconf.get("options", {}) if isinstance(mconf, dict) else {}
  256. url, headers, body = protocol.build_request(
  257. base_url, model_id, messages,
  258. max_tokens=max_tokens,
  259. temperature=temperature,
  260. stream=stream,
  261. extra_headers=extra_headers,
  262. model_options=model_options,
  263. )
  264. if stream:
  265. return self._stream_call(url, headers, body, protocol, timeout)
  266. else:
  267. return self._sync_call(url, headers, body, protocol, timeout)
  268. def _sync_call(self, url, headers, body, protocol: Protocol, timeout: float) -> str:
  269. with httpx.Client(timeout=timeout) as client:
  270. resp = client.post(url, headers=headers, json=body)
  271. if resp.status_code != 200:
  272. print(f"Error {resp.status_code}: {resp.text}", file=sys.stderr)
  273. sys.exit(1)
  274. return protocol.extract_text(resp.json())
  275. def _stream_call(self, url, headers, body, protocol: Protocol, timeout: float) -> str:
  276. collected: list[str] = []
  277. with httpx.Client(timeout=timeout) as client:
  278. with client.stream("POST", url, headers=headers, json=body) as resp:
  279. if resp.status_code != 200:
  280. resp.read()
  281. print(f"Error {resp.status_code}: {resp.text}", file=sys.stderr)
  282. sys.exit(1)
  283. buffer = ""
  284. for chunk in resp.iter_text():
  285. buffer += chunk
  286. while "\n" in buffer:
  287. line, buffer = buffer.split("\n", 1)
  288. line = line.strip()
  289. if not line or line.startswith(":"):
  290. continue
  291. if line.startswith("data: "):
  292. data_str = line[6:]
  293. if data_str.strip() == "[DONE]":
  294. break
  295. try:
  296. data = json.loads(data_str)
  297. delta = protocol.extract_stream_delta(data)
  298. if delta:
  299. print(delta, end="", flush=True)
  300. collected.append(delta)
  301. except json.JSONDecodeError:
  302. continue
  303. print() # newline after stream
  304. return "".join(collected)
  305. # ---------------------------------------------------------------------------
  306. # CLI entrypoint
  307. # ---------------------------------------------------------------------------
  308. def main():
  309. parser = argparse.ArgumentParser(
  310. description="Call LLM APIs using config from the active MiniMax Code data directory",
  311. formatter_class=argparse.RawDescriptionHelpFormatter,
  312. epilog="""
  313. Examples:
  314. %(prog)s --model azure/gpt-5.4 --system "Be brief" --prompt "What is AI?"
  315. echo "Summarize" | %(prog)s --model gemini/gemini-2.5-pro
  316. %(prog)s --list # list available models
  317. %(prog)s --prompt "Hello" # uses defaultModel from config
  318. """,
  319. )
  320. parser.add_argument("--config", type=str, default=None,
  321. help="Path to config.yaml (default: active dataDir/config.yaml, normally ~/.minimax/config.yaml)")
  322. parser.add_argument("--model", "-m", type=str, default=None,
  323. help="Model in provider/model format")
  324. parser.add_argument("--prompt", "-p", type=str, default=None,
  325. help="User prompt text")
  326. parser.add_argument("--system", "-s", type=str, default=None,
  327. help="System prompt")
  328. parser.add_argument("--max-tokens", type=int, default=4096,
  329. help="Max output tokens (default: 4096)")
  330. parser.add_argument("--temperature", "-t", type=float, default=None,
  331. help="Sampling temperature")
  332. parser.add_argument("--timeout", type=float, default=120.0,
  333. help="HTTP request timeout in seconds (default: 120)")
  334. parser.add_argument("--stream", action="store_true",
  335. help="Stream the response")
  336. parser.add_argument("--list", "-l", action="store_true",
  337. help="List available models and exit")
  338. parser.add_argument("--json", action="store_true",
  339. help="Output as JSON (non-streaming only)")
  340. args = parser.parse_args()
  341. caller = LLMCaller(config_path=args.config)
  342. # --list: just show models
  343. if args.list:
  344. models = caller.list_models()
  345. if args.json:
  346. print(json.dumps(models, indent=2, ensure_ascii=False))
  347. else:
  348. for m in models:
  349. marker = " (default)" if m["default"] else ""
  350. print(f" {m['ref']} — {m['name']}{marker}")
  351. return
  352. # Get prompt from arg or stdin
  353. prompt = args.prompt
  354. if not prompt and not sys.stdin.isatty():
  355. prompt = sys.stdin.read().strip()
  356. if not prompt:
  357. print("Error: --prompt is required (or pipe via stdin)", file=sys.stderr)
  358. sys.exit(1)
  359. # Model selection: explicit --model or fall back to defaultModel from config
  360. model_ref = args.model
  361. if not model_ref:
  362. if caller.default_model:
  363. model_ref = caller.default_model
  364. print(f"Using default model: {model_ref}", file=sys.stderr)
  365. else:
  366. print("Error: --model is required (no defaultModel configured in config.yaml)",
  367. file=sys.stderr)
  368. sys.exit(1)
  369. # Build messages
  370. messages: list[dict[str, str]] = []
  371. if args.system:
  372. messages.append({"role": "system", "content": args.system})
  373. messages.append({"role": "user", "content": prompt})
  374. # Call
  375. result = caller.call(
  376. model_ref, messages,
  377. max_tokens=args.max_tokens,
  378. temperature=args.temperature,
  379. stream=args.stream,
  380. timeout=args.timeout,
  381. )
  382. if not args.stream:
  383. if args.json:
  384. print(json.dumps({"model": model_ref, "response": result}, indent=2,
  385. ensure_ascii=False))
  386. else:
  387. print(result)
  388. if __name__ == "__main__":
  389. main()