How yahyamomtaz/biolab-agent-planner works
1. Overall shape
- This repo is a starter stack for an autonomous lab agent, not a generic app.
- The core architectural idea is: natural-language request in, tool-using agent in the middle, structured lab protocol / analysis out.
- Around that core are three delivery surfaces: a FastAPI service, a Gradio UI, and an evaluation harness.
2. Primary runtime boundary
- The main application code lives under src/biolab_agent/.
- BaseAgent defines the contract; BaselineAgent is the reference implementation.
- The active agent is selected via BIOLAB_AGENT_CLASS, so the rest of the stack can stay fixed while swapping agent implementations.
3. Request-to-result flow
- Requests enter through /ask, the CLI benchmark runner, or the UI.
- The agent runs a multi-turn loop, calling tools as needed and then assembling an AgentResult.
- That result contains the human-facing answer, structured payload, citations, and a tool trace, which is what downstream surfaces render or score.
4. LLM orchestration layer
- The baseline agent uses Ollama-hosted MedGemma-4B for tool selection and response synthesis.
- The agent forces a JSON-only interaction pattern: either a tool call or a final answer.
- This makes the model the driver of branching and sequencing, while Python only dispatches tools and records results.
5. Tool subsystem
- Tool implementations live under src/biolab_agent/tools/.
- The four important tools map directly to the benchmark tasks:
- segmentation of microscopy wells,
- protocol retrieval,
- reagent lookup,
- structured protocol composition.
- This is the main functional boundary in the repo: the agent decides what to do; the tools perform deterministic work.
6. Segmentation pipeline
- src/biolab_agent/segmentation/ handles image-based analysis using SAM-backed mask generation.
- It consumes image IDs from data/images/ and returns cell counts, masks, and confluency estimates.
- These outputs are treated as trustworthy structured data and are aggregated back into the final response rather than being left for the LLM to restate from memory.
7. Retrieval / RAG subsystem
- src/biolab_agent/rag/ plus the retrieve_protocol tool provide retrieval over the protocol corpus.
- The corpus is built from data/protocols/opentrons.jsonl, indexed into Qdrant, and queried with embeddings from a sentence-transformer model.
- This is the main external-data integration path for protocol guidance, and it returns source identifiers for citation and scoring.
8. Reagent catalog lookup
- data/reagents/catalog.csv is a lightweight local knowledge base extracted from protocols.
- The reagent tool is intentionally simple: a local substring/catalog search rather than a model-mediated lookup.
- This keeps reagent references deterministic and easy to score against benchmark expectations.
9. Protocol composition and validation
- Structured protocol creation is handled as a typed/validated output boundary, not free-form text.
- compose_protocol(...) and the schemas in src/biolab_agent/schemas.py enforce the shape of the final protocol object.
- This boundary matters because the repository distinguishes “LLM-generated prose” from “validated structured lab plan.”
10. Adapter polish path
- For protocol-design tasks, the agent can optionally unload the Ollama model and run one refinement pass using a LoRA adapter from artifacts/lora-protocol-text/.
- That adapter is loaded through Hugging Face / transformers, separate from the main Ollama inference path.
- This creates a distinct “base reasoning” vs. “final polishing” stage in the architecture.
11. Serving and interfaces
- src/biolab_agent/server.py exposes the service API, while ui/app.py provides a Gradio front end.
- Both are thin shells around the same agent contract and AgentResult schema.
- The repo also includes readiness and liveness endpoints, which reflect dependency health for Ollama and Qdrant.
12. Evaluation and benchmarking
- eval/harness.py and eval/metrics.py define the benchmark loop and scoring rules.
- The benchmark uses the public task set in data/queries_public.yaml and compares against ground truth from the microscopy counts, protocol IDs, and reagent catalog.
- This evaluation layer is a first-class subsystem, not an afterthought, and it shares the same agent entry point as the app.
13. Data and artifact boundaries
- The repo bundles three main data domains: microscopy images, protocol texts, and reagent catalog entries.
- The data/ tree is the source of truth for retrieval, segmentation evaluation, and reagent scoring.
- artifacts/ holds model artifacts such as the LoRA adapter, separating immutable training outputs from source code.
14. Deployment topology
- The stack is containerized with Docker Compose.
- Typical deployment includes the app container plus Ollama and Qdrant sidecars; there is also a CPU-only override and a host-Ollama override.
- This means the architecture intentionally externalizes model serving and vector storage rather than embedding them in-process.
15. Fine-tuning pipeline
- src/biolab_agent/finetune/ and data/finetune/ support LoRA training from protocol-derived instruction pairs.
- The training path is separate from the runtime agent path but feeds the adapter-polarization step used at inference time.
- In other words: corpus → training data → LoRA adapter → optional protocol-design refinement.
16. Config and operational control
- Environment variables in .env.example, plus configs/, control model names, adapter paths, and service wiring.
- Shell scripts under scripts/ wrap setup, data fetching, model pulling, and benchmark execution.
- These are operational glue, but they matter architecturally because they define how the repo’s external dependencies are provisioned and connected.
Main entry points: baseline.py Baseline agent · loader.py Agent loader · harness.py Eval harness · base.py LLM interface
Components 25
Runtime
Agent execution, LLM orchestration, schemas, and service entrypoints.
- CLI · Benchmark and local command-line entrypoint.
src/biolab_agent/cli.py - API server · HTTP service exposing the agent.
src/biolab_agent/server.py - Gradio UI · Human-facing interface wrapping the same agent contract.
ui/app.py - Agent loader · Resolves the active agent implementation from configuration.
src/biolab_agent/agent/loader.py - Agent contract · Shared behavior for all agent implementations.
src/biolab_agent/agent/base.py - Baseline agent · Reference multi-turn agent that orchestrates tools and final responses.
src/biolab_agent/agent/baseline.py - LLM interface · Shared model-client boundary for Ollama and Hugging Face backends.
src/biolab_agent/llm/base.py - Ollama client · Primary inference path for the baseline agent.
src/biolab_agent/llm/ollama_client.py - HF client · Loads the LoRA adapter for optional protocol refinement.
src/biolab_agent/llm/hf_client.py - Schemas · Validated request and result objects, including structured protocols.
src/biolab_agent/schemas.py
Tools
Deterministic capabilities used by the agent.
- Segment tool · Invokes image segmentation and returns counts and confluency.
src/biolab_agent/tools/segment.py - Retrieve tool · Queries protocol retrieval for citations and guidance.
src/biolab_agent/tools/rag.py - Reagent tool · Performs local reagent catalog lookup.
src/biolab_agent/tools/reagents.py - Compose tool · Builds structured protocol outputs.
src/biolab_agent/tools/compose.py - Segmentation · SAM-backed mask generation and measurement pipeline.
src/biolab_agent/segmentation/sam_backend.py - RAG ingest · Builds and queries the protocol retrieval corpus.
src/biolab_agent/rag/ingest.py
Data
Protocol, image, reagent, and training corpora.
- Protocols · Source protocol corpus used for retrieval and training.
data/protocols/opentrons.jsonl - Images · Microscopy inputs and ground truth for segmentation.
data/images/ground_truth.json - Reagents · Local reagent reference table.
data/reagents/catalog.csv - Finetune data · Training and evaluation pairs for adapter learning.
data/finetune/train.jsonl
Evaluation
Benchmarking and scoring against public tasks.
- Eval harness · Drives public tasks through the same agent entrypoint.
eval/harness.py - Metrics · Compares outputs against task-specific ground truth.
eval/metrics.py
Infrastructure
Fine-tuning, adapters, and deployment wiring.
- Finetune · Creates protocol-oriented LoRA adapters.
src/biolab_agent/finetune/train.py - Config · Environment and deployment wiring for models and services.
src/biolab_agent/config.py - LoRA adapter · Protocol-polishing adapter used during optional refinement.
artifacts/lora-protocol-text/adapter_model.safetensors
Connections 26
- CLI → Agent loader: start · CLI resolves the active agent before running benchmarks or local requests.
- API server → Agent loader: start · API server loads the configured agent implementation.
- Gradio UI → Agent loader: start · Gradio UI uses the same agent loader as the service.
- Agent loader → Agent contract: instantiate · Loader binds the chosen implementation to the common contract.
- Agent contract → Baseline agent: default · Baseline agent is the reference implementation of the contract.
- Baseline agent → LLM interface: uses · Agent depends on the shared model-client abstraction.
- LLM interface → Ollama client: runtime · Primary runtime model backend.
- LLM interface → HF client: adapter · Optional Hugging Face path for adapter-based refinement.
- Baseline agent → Segment tool: calls · Agent invokes segmentation when image analysis is needed.
- Baseline agent → Retrieve tool: calls · Agent retrieves protocol guidance and citations.
- Baseline agent → Reagent tool: calls · Agent looks up reagents through a deterministic catalog search.
- Baseline agent → Compose tool: calls · Agent assembles structured protocol outputs through the compose boundary.
- Segment tool → Segmentation: delegates · Tool delegates image processing to the SAM-backed pipeline.
- Retrieve tool → RAG ingest: queries · Retrieval tool queries the indexed protocol corpus.
- RAG ingest → Protocols: builds · Protocol corpus is the source for indexing and retrieval.
- Segmentation → Images: reads · Segmentation consumes microscopy inputs and ground truth assets.
- Reagent tool → Reagents: reads · Reagent lookup is backed by the local catalog.
- Compose tool → Schemas: validates · Structured protocol composition is enforced by schemas.
- Baseline agent → Schemas: returns · Agent emits validated AgentResult objects and structured payloads.
- Eval harness → Baseline agent: runs · Benchmark harness drives the same agent entrypoint as the app.
- Eval harness → Metrics: scores · Harness uses scoring rules to evaluate outputs.
- Eval harness → Finetune data: loads · Public benchmark tasks provide the evaluation set and training sources.
- Finetune → Finetune data: trains on · Fine-tuning consumes instruction pairs derived from protocol data.
- Finetune → LoRA adapter: produces · Training outputs the optional LoRA adapter artifact.
- HF client → LoRA adapter: loads · Adapter backend loads the saved LoRA weights for refinement.
- Config → Baseline agent: configures · Environment config controls agent class selection and model wiring.