swarm-agent README

The project's README from github.com/lyt2003-yt/swarm-agent. As one markdown file: README.md.

SwarmAgent

中文文档

A conversational drone-swarm choreography agent built on the ReAct paradigm, running on top of a deployed SwarmGPT service. It turns natural-language requests ("choreograph this song, make the second section gentler") into validated swarm trajectories — and ships a 1.5B distilled Qwen model (LoRA adapter) that replaces the cloud teacher for choreography planning.

Zero third-party dependencies for the core agent (pure Python stdlib); no changes to the upstream swarmGPT repo required.

Architecture

User (CLI / Web UI)
   │
   ▼
Reasoning (agent.py) ── LLM planner: swarmgpt-qwen (Ollama, format=json_schema hard constraint)
   │  {"thought","action","args"}      falls back to a deterministic state machine on failure
   ▼
Act (tools.py) ── HTTP calls to the existing SwarmGPT API (127.0.0.1:8000)
   │  list_songs / list_models / generate_choreography /
   │  best_of_n_choreography / refine_choreography / get_playback_summary
   ▼
Observation (observation.py) ── rule-based validator
   │  {pass, score, issues[], suggested_next_action}
   └────────────── feedback to Reasoning ──────────────┘

Repository layout

Path Contents
agent.py / tools.py / observation.py ReAct loop, tool wrappers, rule-based validator
main.py CLI entry point (interactive & one-shot)
webui/ Web chat UI (Vue 3 frontend + FastAPI server)
distill/ Distillation pipeline: teacher data collection, SFT (QLoRA), DPO
distill/ckpt/lora_adapter/ Open-sourced distilled model — LoRA adapter for Qwen/Qwen2.5-1.5B-Instruct
eval/ Evaluation harness, configs, and report

Prerequisites (services you need running)

Service Port Start
SwarmGPT API 8000 cd swarmGPT && pixi run api
Ollama 11434 ollama serve
(optional) Bailian proxy 8355 python3 ../bailian_proxy.py

A swarmgpt-qwen model should be registered in Ollama (qwen2.5:7b + 32k ctx, see the Modelfile in the parent project). The planner backend is configurable — see below.

Usage

cd swarmAgent
python3 main.py              # interactive chat
python3 main.py --once "Generate choreography for Crazyflie Drones Theme (short)"

Example prompts:

After a successful generation, open http://127.0.0.1:8000 for the 3D playback (latest job). The webui/ directory provides a standalone chat + playback web interface (python3 webui/server.py).

Configuration (config.json)

Key Description
planner_model Planner model (Ollama tag)
choreo_provider / choreo_model Choreography backend (ollama / openai via Bailian proxy)
best_of_n Best-of-N sample count (4 recommended locally, 2–4 for cloud)
max_iters Max ReAct iterations (runaway guard)

Distilled model (LoRA adapter)

distill/ckpt/lora_adapter/ contains a QLoRA adapter (r=8, alpha=16) distilled from a cloud teacher (Qwen-Max via Bailian) onto Qwen2.5-1.5B-Instruct, trained on the agent's own session logs (distill/sft_train.jsonl) plus DPO pairs (distill/dpo_pairs.jsonl). It runs on a 6 GB GPU.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

base = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-1.5B-Instruct", torch_dtype=torch.float16, device_map="auto")
model = PeftModel.from_pretrained(base, "distill/ckpt/lora_adapter")
tokenizer = AutoTokenizer.from_pretrained("distill/ckpt/lora_adapter")

To reproduce training (scripts in distill/):

python distill/gen_teacher_data.py    # 1. collect teacher demonstrations
python distill/prepare_sft.py         # 2. build SFT dataset
python distill/train_lora.py          # 3. QLoRA SFT
python distill/collect_dpo_pairs.py   # 4. collect DPO preference pairs
python distill/train_dpo.py           # 5. DPO alignment

Evaluation

eval/ contains the baseline harness (run_eval.py, analyze.py) measuring single-shot success rate, Best-of-N marginal returns, and failure-mode distribution across local and cloud models. See eval/report.md for results.

Logging & data flywheel

logs/session_*.jsonl (gitignored) records every thought/action/observation — the training data source for SFT/DPO distillation.

License & acknowledgements

Built on top of the SwarmGPT project. The distilled adapter is derived from Qwen2.5-1.5B-Instruct — please comply with the Qwen license.

swarm-agent (lyt2003-yt/swarm-agent)

Searching Database…

Что это?SwarmAgent — разговорный агент, превращающий запросы на естественном языке вроде «поставь хореографию на эту песню, сделай вторую часть мягче» в проверенные траектории роя дронов; он построен на парадигме ReAct и работает поверх отдельно развёрнутого сервиса SwarmGPT.
Это только CLI-инструмент или есть и чат-интерфейс?Это Python CLI-агент (main.py, интерактивный или одноразовый), к которому прилагается отдельный веб-чат на Vue 3 + FastAPI с 3D-проигрыванием сгенерированной хореографии.
Как это запустить?Сначала запустите API SwarmGPT («cd swarmGPT && pixi run api», порт 8000) и Ollama («ollama serve», порт 11434), зарегистрировав в Ollama модель «swarmgpt-qwen», затем выполните main.py для CLI или «python3 webui/server.py» для веб-интерфейса.
Нужны ли самому агенту дополнительные Python-пакеты?У основного агента ноль сторонних зависимостей — он работает на чистой стандартной библиотеке Python, но для реальной генерации хореографии всё равно нужны работающий API SwarmGPT и экземпляр Ollama с зарегистрированной моделью swarmgpt-qwen (qwen2.5:7b, контекст 32k).
Какой главный нюанс, прежде чем им можно пользоваться?Это не самостоятельный инструмент — придётся отдельно развернуть и запустить исходный проект SwarmGPT, а также поднять Ollama с моделью планировщика, прежде чем агент сможет выдавать какие-либо траектории.
Что такое SwarmGPT и зачем запускать его отдельно?SwarmGPT — это исходный сервис, который собственно генерирует и проверяет траектории роя; SwarmAgent — клиент на базе ReAct, вызывающий его API (порт 8000), чтобы превращать чат-запросы в хореографию дронов.
Что делает «Best-of-N sampling», когда я прошу поставить хореографию на песню?Планировщик генерирует несколько вариантов траекторий (количество задаёт bestofn, локально рекомендуется 4), применяет фильтрацию безопасности, оценивает их и автоматически выбирает лучший.
Зачем поставлять дистиллированную модель на 1.5B вместо постоянных обращений к облачному учителю?LoRA-адаптер (QLoRA, r=8/alpha=16), дистиллированный из Qwen-Max, позволяет планировать хореографию на локальном GPU с 6 ГБ вместо зависимости от платного облачного API, воспроизводя поведение учителя по собственным логам агента.
Откуда берутся обучающие данные для дистиллированной модели?Каждая мысль/действие/наблюдение ReAct пишется в logs/session.jsonl, откуда питаются sfttrain.jsonl и dpopairs.jsonl — самогенерируемый маховик данных для пайплайна дистилляции SFT/DPO.
Creator
lyt2003-yt
Size
16.8 MB
Stars
190
Updated
CommitAug 21
Age
1mo
Commits · 90 Days