# Using the Ambient Agent for proactive video annotation A practical guide for agents that need to turn egocentric task videos into structured, **proactive** assistant walkthroughs (timestamped decision + utterance events). Written from a working setup; every gotcha below was hit and fixed in practice. --- ## 1. What it produces The ambient agent (`ambient/agent.py::run_agent`) is a **tool-calling video agent**. Given a video and the annotation prompt, it inspects the video across several turns with vision tools, then emits a rich JSON walkthrough: ``` task_name / goal / (procedure) walkthrough: [ {timestamp, decision, interaction_type, visible_context, utterance, timing_rationale, confidence, linked_user_response, ...}, ... ] silent_intervals: [ {start_time, end_time, reason}, ... ] failure_modes: [...] ``` `decision` ∈ `intervene | correct | confirm | redirect | insist | observe | complete`. Timestamps are real seconds (not fixed chunks). This is dramatically richer than a single-pass VLM labeling (e.g. on 4 egoconv clips: single-pass gave 0–7 cues/clip; the agent gave 8–15 decision-typed events + silent intervals, and it *infers the task from the video* — e.g. a "HomeDIY"-labeled clip → "Bedroom Organization and Desk Tidying"). The reference prompt is **`annotation_prompt.txt`** (5-stage: retrospective understanding → action timeline → intervention opportunities → walkthrough → validation, with a strict causal constraint: each utterance justified only by evidence up to its timestamp). --- ## 2. Two models, two endpoints | role | config field | example | what it does | |---|---|---|---| | **orchestrator** | `agent_model` @ `agent_base_url`/`agent_api_key` | `deepseek/deepseek-v4-flash` (OpenRouter) | drives the tool-calling loop, writes the walkthrough | | **vision** | `llm_model` @ `llm_base_url`/`llm_api_key` | `nvidia/Qwen3.6-27B-NVFP4` (local vLLM) or `qwen/qwen3.6-27b` (OpenRouter) | analyzes clips for `focus_clip`/`search_clip` | > The orchestrator only needs text (tool results are text descriptions), so keep it on a cheap capable > model. The vision model is the cost/quality driver — self-host it to cut cost ~10×. **Endpoint split:** by default `run_agent` sent *both* calls to `llm_base_url`. It's patched (`agent.py`, ~line 357) so the agent uses `agent_base_url` when set, vision keeps `llm_base_url`. This lets you run **vision on a local GPU** and the **orchestrator on OpenRouter** simultaneously. --- ## 3. Deployment: local-GPU vision (recommended — cheap + fast) Serve the vision model with the **vLLM Docker image** (no host installs; the container survives ssh-close, which sidesteps the VM process-persistence trap below). On a Blackwell GPU, use the NVFP4 build (native FP4, ~14 GB, fast): ```bash docker run -d --name qwenvis --gpus all --ipc=host -p 8000:8000 \ -v ~/hf_cache:/root/.cache/huggingface \ vllm/vllm-openai:latest \ --model nvidia/Qwen3.6-27B-NVFP4 --served-model-name nvidia/Qwen3.6-27B-NVFP4 \ --trust-remote-code --gpu-memory-utilization 0.85 --max-model-len 32768 \ --limit-mm-per-prompt '{"image":32}' # vision tools send ~28 frames/call — set this high ``` Wait for readiness: `curl http://localhost:8000/v1/models` → 200. For a **public** endpoint, the host binds `0.0.0.0:8000`; reach it at `http://:8000` (open the port if firewalled). Then point the agent box's `.env` at it. ### `.env` (on the box running the agent) ```dotenv LLM_BASE_URL=http://:8000/v1 # vision (local vLLM) LLM_MODEL=nvidia/Qwen3.6-27B-NVFP4 LLM_API_KEY=EMPTY AGENT_BASE_URL=https://openrouter.ai/api/v1 # orchestrator AGENT_API_KEY=sk-or-... AGENT_MODEL=deepseek/deepseek-v4-flash SANDBOX_BACKEND=inprocess # local ffmpeg (needs ffmpeg on PATH) INLINE_CLIPS=true # no S3: clips embedded inline VIDEO_FOLDER=/abs/path/to/videos # run_agent globs VIDEO_FOLDER/* ``` **OpenRouter-only alternative** (no GPU, simpler, ~10× the cost): set both `LLM_*` and `AGENT_*` to OpenRouter, `LLM_MODEL=qwen/qwen3.6-27b`. See cost table in §7. ### Deps for the agent process (not the vLLM container) `aiohttp tenacity pydantic pydantic-settings boto3 rich python-dotenv` + `ffmpeg` on PATH. (`boto3` is imported transitively even with `INLINE_CLIPS=true`.) --- ## 4. Driving it (the calling pattern) `run_agent(video_id, question, max_turns, output_structure)` runs the loop. Give it a Pydantic `output_structure` (its JSON schema is appended to the prompt) and read the answer **from the trajectory file** (see gotcha #2). ```python from ambient.agent import run_agent from pydantic import BaseModel, Field class Walk(BaseModel): walkthrough: list[dict]; silent_intervals: list[dict] = [] task_name: str = ""; goal: str = "" q = open("annotation_prompt.txt").read() + f""" # This input Video id: {stem}. High-level task: a {task} activity. ~{dur:.0f}s. TOOL BUDGET: inspect with AT MOST 5 focus_clip/search_clip calls (beginning / key middle / end). Then STOP calling tools and output ONLY the final JSON walkthrough — no prose. Timestamps in 0..{dur:.0f}s. """ msgs = await run_agent(video_id=stem, question=q, max_turns=12, output_structure=Walk) ann = answer_from_trajectory(stem) # read the final JSON from ambient/trajectories/**.json ``` Run clips **concurrently** with `asyncio.gather` — they're independent (separate video_id, trajectory, frame cache), and the bottleneck is model latency, so it's ~N× faster. --- ## 5. Gotchas (each cost real time — do these) 1. **Image-only vision models reject `video_url`.** `construct_payload` sends clips as a base64 `video_url`; only gemini-class models accept that. For qwen (image-only) it fails with `ClientConnectionError`. **Fix (already patched in `ambient/llm.py`):** when the model isn't gemini, sample frames from the clip mp4 and send `image_url` blocks instead. Keep `--limit-mm-per-prompt` image budget ≥ the frames/call (~28). 2. **The final answer is NOT in `run_agent`'s return.** On `end_turn` the loop `break`s without appending the final assistant message to `messages`. Read it from the **trajectory file** (`ambient/trajectories/trajectory__*.json`, last turn's `text`); strip ```` ```json ```` fences, take the largest balanced `{...}` containing `walkthrough`. 3. **Bound the tool budget or it never answers.** Without "use ≤5 tools then output JSON", the agent spends all `max_turns` inspecting and emits no final JSON (looks like a parse failure). Put the budget in the question; `max_turns=12` is comfortable. 4. **Don't trust clip metadata durations — `ffprobe`.** egoconv `duration_in_sec` is unreliable (says 64–92 s; real videos are ~300 s). Probe the actual file. And when globbing for the file, **match the video extension** — `glob("*")[0]` can hit the `/` frames dir the tools create and crash `ffprobe`. 5. **Process persistence on the VMs.** Detached processes (nohup/setsid/tmux) get killed on ssh-close even with `loginctl enable-linger` (they stay in the session cgroup scope). Two robust options: run the workload in a **Docker container** (survives), or **hold the ssh open from your side** as a background task. `systemd-run --scope`/`--user` is the "proper" fix but was flaky here. 6. **`pgrep -f ` matches your own command** (the pattern is in your cmdline). Don't use it to decide "is it running" — check a log marker or a PID. 7. **Vision reasoning verbosity.** qwen3.6-27b is a reasoning model; give tool/vision calls enough `max_tokens` (≥2k) and strip `…` before JSON parsing. Don't disable thinking unless asked — longer `max_tokens` is the fix. --- ## 6. Output → training labels To convert a walkthrough into per-8s-chunk `$interrupt$/$silent$` proactive labels: bin `walkthrough` events by `int(timestamp // 8)` → that chunk is `$interrupt$`; all others `$silent$`. `silent_intervals` are a cross-check. `decision` types map naturally (intervene/correct/redirect/insist → interrupt; observe/confirm are optional). Frames for training come from the same videos. --- ## 7. Cost & scale (measured) Per clip: ~7.5 vision calls (≈28 frames each) + ~4 orchestrator turns. | vision backend | $/clip | 235 clips | notes | |---|---|---|---| | OpenRouter `qwen3.6-27b` | ~$0.12–0.15 | ~$30–35 | reasoning *output* @ $3.60/M dominates | | **local NVFP4 (Docker)** | **~$0.015** | **~$3.5** | only deepseek on OpenRouter; ~10× cheaper + no rate limits | Wall-clock ~5 min/clip; concurrent (~10) ≈ ~2 clips/min → ~2–3 h for 235 clips. Videos must be on the agent box (`VIDEO_FOLDER`); ~8 GB for 235 egoconv clips. --- ## 8. Quick start (local-GPU path) ```bash # 1. vision server (GPU box, Docker) — see §3, wait for /v1/models = 200, open the port # 2. agent box: put ambient_agent/ + videos there; write .env (§3); install deps (§3) # 3. drive it (§4) with annotation_prompt.txt, concurrent via asyncio.gather # 4. read ann from ambient/trajectories/* (gotcha #2) ``` Reference working driver: `annotate_egoconv.py` (probe+ffprobe, trajectory extraction, tool budget, concurrent gather). Reference prompt: `annotation_prompt.txt`.