Datasets:
File size: 9,341 Bytes
371b96b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | # 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://<host-ip>: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://<gpu-host>: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/<video_id>*
```
**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/*<stem>*.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_<video_id>_*.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("<stem>*")[0]` can hit the `<stem>/` 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 <name>` 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 `<think>…</think>` 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$<utterance>`; 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`.
|