"""Standalone vision worker.

The text model (8B) and the vision model (7B) do not fit in the unified memory of
a 16 GB machine at the same time, so image inspection runs in a short lived
subprocess: it loads the vision model, answers one question and exits, releasing
the memory again.

Usage:
    python -m gaia_agent.vlm_worker --image <path> --question "..." [--max-tokens 400]
"""

from __future__ import annotations

import argparse
import os
import sys

DEFAULT_MODEL = os.getenv("GAIA_VLM_MODEL", "mlx-community/Qwen2.5-VL-7B-Instruct-4bit")


def main() -> int:
    parser = argparse.ArgumentParser(description="Ask a vision model about one image.")
    parser.add_argument("--image", required=True)
    parser.add_argument("--question", required=True)
    parser.add_argument("--model", default=DEFAULT_MODEL)
    parser.add_argument("--max-tokens", type=int, default=400)
    args = parser.parse_args()

    from mlx_vlm import load
    from mlx_vlm.generate import batch_generate

    model, processor = load(args.model)
    # ``batch_generate`` is the code path the mlx-vlm CLI uses: it applies the chat
    # template and the vision placeholders itself, so the prompt stays raw text.
    response = batch_generate(
        model,
        processor,
        images=[args.image],
        prompts=[args.question],
        max_tokens=args.max_tokens,
        verbose=False,
    )
    texts = getattr(response, "texts", None) or []
    print(str(texts[0]).strip() if texts else "")
    return 0


if __name__ == "__main__":
    sys.exit(main())
