Repository navigation
Created an agents.md file for working in or with the pyares library #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| # AGENTS.md — Repository Navigation Context for PyAres | ||
|
|
||
| Context for AI agents and human contributors working **in** (maintaining/extending) | ||
| or **with** (consuming/implementing services for) the **PyAres** library. | ||
|
|
||
| --- | ||
|
|
||
| ## 1. What This Project Is | ||
|
|
||
| **PyAres** is the official Python SDK and gRPC service framework for the **ARES** | ||
| self-driving laboratory ecosystem. It bridges native Python | ||
| code with the centralized [ARES OS 2](https://github.com/AFRL-ARES/ARES) orchestrator using | ||
| Protocol Buffers and gRPC via [`ares-datamodel`](https://github.com/AFRL-ARES/ares-datamodel). | ||
| Official documentation for all aspects of the ARES ecosystem is located on the [Docs Page](https://afrl-ares.github.io/). | ||
|
|
||
| PyAres abstracts away raw Protobuf messages and gRPC boilerplate, exposing clean, | ||
| idiomatic Python interfaces to implement four core service archetypes: | ||
|
|
||
| 1. **Device Services (`AresDeviceService`)** — Control laboratory hardware, actuators, | ||
| and sensors; expose executable commands, schemas, and live telemetry; implement safety | ||
| interlocks and safe-mode procedures. | ||
| 2. **Planning Services (`AresPlannerService`)** — Drive experimental campaigns using | ||
| optimization algorithms, active learning, Bayesian optimization, heuristic search, etc. | ||
| to suggest the next parameter values to evaluate. | ||
| 3. **Analysis Services (`AresAnalyzerService`)** — Extract quantitative objectives and | ||
| metrics from raw experimental outputs, passing structured results to planners and ARES OS. | ||
| 4. **Visualizer Services (`AresVisualizerService`)** — Render charts and dashboard widgets | ||
| (e.g., Plotly figures) for display in the ARES OS web interface. | ||
|
|
||
| --- | ||
|
|
||
| ## 2. Python Environment & Build System | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This section gives me some minor concerns simply because outlining specific versions means suddenly our agents.md becomes an additional place that needs updated every time that we update our packages. I'd recommend instead supplying direction to an agent to check the .toml file to understand the dependencies instead. |
||
|
|
||
| - **Consult TOML for Dependencies and Build Info** The `pyproject.toml` file in the repository root file serves | ||
| as the single source of truth for dependencies and build information. | ||
| - **Dynamic Versioning**: The [`hatchling`](https://hatch.pypa.io/) build back ends reads the package version | ||
| dynamically from the `PYARES_PACKAGE_VERSION` environment variable (required during `build` or `pip install -e .`): | ||
| ```bash | ||
| export PYARES_PACKAGE_VERSION="0.0.1" # or matching release tag | ||
| ``` | ||
|
|
||
| ### Development & Testing Setup | ||
|
|
||
| ```bash | ||
| # Clone and enter repo | ||
| cd PyAres | ||
|
|
||
| # Set version for hatchling | ||
| export PYARES_PACKAGE_VERSION="0.0.1" | ||
|
|
||
| # Install in editable mode with test dependencies | ||
| pip install -e . | ||
| pip install grpcio grpcio-tools protobuf pytest | ||
|
|
||
| # Run full test suite | ||
| pytest -v tests/ | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 3. Repository Layout & Code Map | ||
|
|
||
| ``` | ||
| PyAres/ | ||
| ├── pyproject.toml # Hatchling build specification & dependencies | ||
| ├── README.md # Upstream package summary & centralized docs link | ||
| ├── AGENTS.md # This File | ||
| ├── LICENSE # MIT License | ||
| ├── .github/workflows/ # CI/CD: unit tests (ubuntu, py3.10) & PyPI publishing | ||
| ├── tests/ # Unit tests & MockGrpcContext | ||
| └── PyAres/ # Root package directory | ||
| ├── __init__.py # Public top-level API exports | ||
| ├── Device/ # Hardware control service framework | ||
| │ ├── device_service.py # AresDeviceService & AresDeviceServiceWrapper (gRPC servicer) | ||
| │ ├── device_models.py # DeviceCommandDescriptor, DeviceCommandResponse, StatusCode, etc. | ||
| │ └── device_warnings.py # Warning categories for device services | ||
| ├── Planning/ # Campaign & experiment planning framework | ||
| │ ├── planning_service.py # AresPlannerService & AresPlannerServiceWrapper (gRPC servicer) | ||
| │ └── planner_models.py # PlanRequest, PlanResponse, PlanningParameter, Plan, etc. | ||
| ├── Analyzing/ # Experiment evaluation & objective calculation framework | ||
| │ ├── analysis_service.py # AresAnalyzerService & AresAnalyzerServiceWrapper (gRPC servicer) | ||
| │ └── analyzer_models.py # AnalysisRequest, AnalysisResponse, Objective, ObjectiveSchema | ||
| ├── Visualizers/ # UI Visualization rendering framework | ||
| │ ├── visualizer_service.py # AresVisualizerService & AresVisualizerServiceWrapper | ||
| │ └── visualizing_models.py # VisualizationOption, VisualizationRequest, DataPoint | ||
| ├── Models/ # Shared data models & enums | ||
| │ └── ares_data_models.py # AresDataType, Outcome, PlanStatusCode, RequestMetadata, Limits | ||
| ├── Utils/ # Protobuf ↔ Python conversion utilities & base infrastructure | ||
| │ ├── grpc_base.py # AresGrpcServiceBase: server lifecycle, thread pool, message size | ||
| │ ├── ares_service_base.py # AresBaseService & AresServiceWrapperBase: common RPCs & async resolver | ||
| │ ├── metadata_interceptors.py # DatamodelVersionServerInterceptor: handshake version header | ||
| │ ├── ares_value_utils.py # Primitive/AresValue protobuf bi-directional conversion | ||
| │ ├── ares_struct_utils.py # Dict/AresStruct conversion helpers | ||
| │ ├── ares_data_schema_utils.py # Schema builder helpers for inputs, settings, and outputs | ||
| │ ├── ares_data_type_utils.py # AresDataType enum translation | ||
| │ ├── device_status_code_utils.py # Status code mapping & success evaluation | ||
| │ ├── ares_outcome_utils.py # Outcome enum translation | ||
| │ ├── plan_request_utils.py # Protobuf PlanRequest unpacking | ||
| │ └── plan_response_utils.py # Protobuf PlanResponse packaging | ||
| ├── test_tools/ # Standalone test clients | ||
| │ ├── analyzer_tester.py # AnalyzerTestClient: test Analyzer services without ARES OS | ||
| │ └── planner_tester.py # PlannerTestClient: test Planner services without ARES OS | ||
| └── Demo/ # Working reference implementations | ||
| ├── BEST_PRACTICES.md # Best Practcies for PyAres Service Implementations | ||
| ├── Devices/ # Example devices (hotplate, rotary mixer, random generator, etc.) | ||
| ├── Planners/ # Example planners (grid, random, test-tools integration) | ||
| └── Analyzers/ # Example analyzers (basic, Ax analyzer, test-tools integration) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 4. Architectural Patterns & Core Invariants | ||
|
|
||
| ### 4.1 Base Service Inheritance Architecture | ||
| Every service in PyAres (`Device`, `Planning`, `Analyzing`, `Visualizer`) is split into two components: | ||
| 1. **The User-Facing Service (`AresBaseService` subclass)**: | ||
| - Manages the gRPC server lifecycle (`start()`, `stop()`). | ||
| - Configures networking (`port`, `use_localhost`, `max_message_size`). | ||
| - Manages service settings and capability schema declarations. | ||
| 2. **The Internal gRPC Servicer Wrapper (`AresServiceWrapperBase` subclass)**: | ||
| - Implements generated gRPC Servicer stubs from `ares-datamodel`. | ||
| - Exposes standard diagnostic RPCs: `GetInfo`, `GetConnectionStatus`, `GetState`. | ||
| - Intercepts requests, translates protobuf messages to native Python data structures, executes registered callbacks, and packs Python returns back into protobuf responses. | ||
|
|
||
| ### 4.2 Version Handshake & Metadata Interception | ||
| All services run with `DatamodelVersionServerInterceptor` (`PyAres/Utils/metadata_interceptors.py`). | ||
| Every RPC attaches the `datamodel-version` header corresponding to the installed `ares_datamodel` | ||
| version. This ensures ARES OS and external orchestrators can verify protocol compatibility. | ||
|
|
||
| ### 4.3 Async & Sync Callback Support | ||
| User-supplied logic (e.g., `enter_safe_mode`, `plan_logic`, `custom_analysis_logic`, commands) | ||
| can be written as standard synchronous functions or `async` coroutines. The wrapper automatically | ||
| resolves awaitables via `_resolve_awaitable()` (`PyAres/Utils/ares_service_base.py`). | ||
|
|
||
| ### 4.4 Default Port Allocations | ||
| - **Device Service**: `7100` (configurable via `port`) | ||
| - **Planner Service**: `7082` (configurable via `port`) | ||
| - **Analyzer Service**: `7083` (configurable via `port`) | ||
|
|
||
| --- | ||
|
|
||
| ## 5. Best Practices: Working WITH PyAres (Developing Services) | ||
| - Examples and guidelines for implementation best bractices are located in `PyAres/Demos/`. | ||
|
|
||
| --- | ||
|
|
||
| ## 6. Best Practices: Working IN PyAres (Maintaining the Library) | ||
|
|
||
| ### 6.1 Protobuf & Datamodel Compatibility | ||
| - PyAres depends strictly on `ares-datamodel`. Never import raw gRPC files from custom paths; always import from `ares_datamodel...`. | ||
| - If a Protobuf schema in `ares-datamodel` changes, update the translation layers in `PyAres/Utils/` (`ares_value_utils.py`, `ares_struct_utils.py`, `ares_data_schema_utils.py`, etc.) and ensure both forward and backwards compatibility. | ||
|
|
||
| ### 6.2 Backwards Compatibility & Deprecation Policy | ||
| - Many existing laboratory devices run older PyAres conventions. | ||
| - When introducing a new model or schema structure, provide an adapter or backwards compatibility fallback (e.g., how `ExecuteCommand` still accepts legacy raw dict returns and emits a `FutureWarning`, or how `AnalysisResponse` handles legacy `result`). | ||
| - Use Python's `warnings.warn` with `FutureWarning` or `DeprecationWarning` rather than throwing errors on older API patterns. | ||
|
|
||
| ### 6.3 Network Binding & Host Configuration | ||
| - `AresGrpcServiceBase` defaults `use_localhost=True`, binding to `localhost:{port}`. | ||
| - Setting `use_localhost=False` binds to `[::]:{port}` (IPv6 wildcard, allowing LAN access from other host machines). | ||
| - Never hardcode IP addresses or assume external network access. | ||
|
|
||
| ### 6.4 Unit Testing Practices | ||
| - Place unit tests under `tests/`. | ||
| - Name test files `test_*.py`. | ||
| - Use `unittest.TestCase` or `pytest`. | ||
| - Use `MockGrpcContext` (from `tests/mock_grpc_context.py` or inline) to test gRPC servicer logic without needing live socket bindings. | ||
| - When spinning up a real service in a test, always ensure `service.stop()` is invoked in `tearDown()` to release the port. | ||
|
|
||
| --- | ||
|
|
||
| ## 7. Licensing & Clearance | ||
|
|
||
| - **License**: MIT License (see [`LICENSE`](LICENSE)). | ||
| - **Clearance**: AFRL Clearance: *Distribution A. Approved for public release: distribution unlimited. AFRL-2025-5332.* | ||
| - Keep all first-party code MIT licensed. Do not vendor or introduce copyleft/GPL code into PyAres. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| # Best Practices: Working WITH PyAres (Developing Services) | ||
|
|
||
| Context for AI agents and human contributors working **with** | ||
| (consuming/implementing services for) the **PyAres** library. | ||
|
|
||
| ## 0. Directory Structure | ||
|
|
||
| The `PyAres/Demo/` directory contains reference implementations and test clients for PyAres services: | ||
|
|
||
| ```text | ||
| PyAres/Demo/ | ||
| ├── BEST_PRACTICES.md # This File. Service implementation guidelines and best practices | ||
| ├── Analyzers/ # Example analyzer services and test scripts | ||
| │ ├── analyzer_test.py # Basic analyzer implementation example | ||
| │ ├── analyzer_test_tools_demo.py # Standalone analyzer testing with AnalyzerTestClient | ||
| │ ├── analyzer_wiki.py # Reference analyzer returning structured Objective metrics | ||
| │ └── ax_analyzer_test.py # Ground-truth evaluation service for Ax optimization | ||
| ├── Devices/ # Example device services and hardware wrappers | ||
| │ ├── device_test.py # Simulated device with temperature control and state | ||
| │ ├── failure_test_device.py # Device demonstrating intentional failures & error handling | ||
| │ ├── hotplate.py # Virtual hotplate with safe mode, polling, & command schemas | ||
| │ ├── random_number_device.py # Virtual sensor generating random numbers with schemas | ||
| │ └── rotary_mixer.py # Virtual rotary mixer with RPM speed control | ||
| └── Planners/ # Example planning services and test scripts | ||
| ├── planner_test.py # Planner example processing parameter histories & objectives | ||
| ├── planner_test_tools_demo.py # Standalone planner testing with PlannerTestClient | ||
| └── planner_wiki.py # Batch random parameter generation planner | ||
| ``` | ||
|
|
||
| ## 1. General Guidance | ||
|
|
||
| - **Soft Preference for Stateless Services** - When possible, services should be designed to be stateless, treating each request independently, | ||
| and retaining no data between calls. Sometimes, a purely stateless desgin is not possible or may result in large time delays due to computational overhead. For example a service with a persistent connection to hardware or software, a streamed data source, a large database that must be loaded into ram etc. In these cases the execution logic should be contained within a class that initializes and manages the persistent resources either on class instantiation or on the receipt of the first request from ARES | ||
| - **Graceful Closeout and Exception Handling** - Services should always take care to exit gracefully in the case of an exception or manual (ctrl+c)closeout of the service by using try-except-finally control structure. If an exception occured while procesing a request from ARES, this exception should be conveyed back to ARES as part of error handling. When the service involves a connection to an extneral hardware interface, network, or software instance logic should be included to safely close down those connections. Ensure that all child threads or sub-processes spawned by the service are terminated upon closeout. | ||
| - **Object-Oriented Design for More Complex Services** - Any service logic that needs more that 4 or 5 functions or more | ||
| than a few dozen lines of code should be implmented as a class. | ||
| - **Service Portability** - When implemnting a service use a project structure that is suitable for redistribution and installation with package managers such as `pip`. Every service should have documented requirements in a `requirements.txt` or `pyproject.toml` file. If a servce requires proprietary elements that cannot be freely distributed (e.g., an API key, a manufacturer SDK), the service should be structured so that it can interact with user-provided proprietary elements without incorporating them into the redistributable core of the service. | ||
|
|
||
| ## 2 Implementing Device Services (`AresDeviceService`) | ||
|
|
||
| A device service wraps real or simulated hardware to expose actuators and sensors to ARES OS. They are also the most flexible class of servce and can be used execute arbitrary logic that is needed within an ARES Experimental. For example: | ||
|
|
||
| - **Calculations Outside of Analyzers** - When derived values are needed with the experimental loop (e.g., setting a sample acquistion time based on a the system flowrate). | ||
| - **Execution of External Scripts** - When an experimental campaign needs to trigger external actions on the host PC (e.g., compiling software, cleaning up temporary files). | ||
| - **Interactions With External Software** - Call external software APIs (e.g., Initialize or post-process computer simulations). | ||
|
|
||
| Example device implementations can be found in `PyAres/Demo/Devices` | ||
|
|
||
| ### Invariants & Rules for Device Services | ||
|
|
||
| - **Wrap Generic Device Drivers** - When a python compatible device driver is not provided, it is preferable to implement a separate python interface class that handles device communication and top-level commands and then wrap the device in a PyAres compatibility layer used by the device service. This ensures the device is useable with or without PyAres. | ||
| - **Mandatory Safe Mode and Get State Callbacks** - Safe mode and get state callbacks are mandatory on every PyAres device service. Safe mode callbacks must be robust, non-blocking or fast, and idempotent. | ||
| - **Always return `DeviceCommandResponse`**: Returning bare values or raw dictionaries is deprecated and triggers a `FutureWarning`. Always encapsulate return values in `DeviceCommandResponse(status_code=..., response=...)`. | ||
| - **Match Parameter Signatures**: The parameter names and count of your Python callback **must match exactly** with the `input_schema` keys in `DeviceCommandDescriptor`. Mismatches emit warnings or fail at execution. | ||
| - **Fail Gracefully via `StatusCode`**: Do not let unhandled hardware exceptions crash the service. Catch exceptions and return appropriate status codes (`StatusCode.HARDWARE_FAULT`, `StatusCode.COMMAND_FAILED`, `StatusCode.OUT_OF_RANGE`, etc.). | ||
| - **Always Keep `enter_safe_mode` Safe**: The `enter_safe_mode` callback must never throw an unhandled exception; wrap internal calls in `try/except` and ensure it sets physical hardware to a safe state. | ||
|
|
||
| --- | ||
|
|
||
| ## 2 Implementing Planner Services (`AresPlannerService`) | ||
|
|
||
| A planner receives parameter histories and analysis feedback from past experiments and computes | ||
| the next set of parameters to test. | ||
|
|
||
| Example planner implementations can be found in `PyAres/Demo/Planners` | ||
|
|
||
| ### Invariants & Rules for Planner Services | ||
|
|
||
| - **Batch Planning Support**: Planners should check for the number of requested experiments in `PlanRequest.batch_size` to determine how many sets of parameter values to generate and return in the `Plan` object. | ||
| - **Use `request.analysis_data` (Not `request.analysis_results`)**: `PlanRequest.analysis_results` is deprecated. Use `request.analysis_data` or the convenience helper `request.analysis_objectives` to access `Objective` instances. | ||
| - **Provide `parameter_data` Dict or Matched Lists**: Either pass `parameter_data={"key": value}` or pass two lists of equal length: `parameter_names=[...]` and `parameter_values=[...]`. | ||
| - **Stop Campaigns cleanly**: When optimization converges or target thresholds are reached, return `objective_status=ObjectiveStatus.OBJECTIVE_ACHIEVED`. | ||
|
|
||
| --- | ||
|
|
||
| ## 3 Implementing Analyzer Services (`AresAnalyzerService`) | ||
|
|
||
| An analyzer ingests data from an experimental source and produces structured objective values that are used as feedback for experimental planning. | ||
|
|
||
| Example planner implementations can be found in `PyAres/Demo/Analyzers` | ||
|
|
||
| ### Invariants & Rules for Analyzer Services | ||
|
|
||
| - **Return explicit `Objective` instances**: Constructing `AnalysisResponse(result=...)` is deprecated. Always construct `AnalysisResponse(objectives=[Objective(...)], outcome=...)`. | ||
| - **Declare schemas via `add_analysis_parameter` and `add_objective_output`**: Declaring input and output schemas allows ARES OS to validate compatibility before starting campaigns. | ||
|
|
||
| --- | ||
|
|
||
| ## 4 Standalone Testing with `test_tools` | ||
|
|
||
| PyAres provides built-in standalone test clients in `PyAres.test_tools` so you can verify services | ||
| without running the entire ARES OS orchestrator: | ||
|
|
||
| - `AnalyzerTestClient(port=7083, host='localhost')`: Test `get_info()`, `check_status()`, and `run_analysis(inputs, settings)`. | ||
| - `PlannerTestClient(port=7082, host='localhost')`: Test `get_info()`, `check_status()`, and `run_planning(request)`. | ||
|
|
||
| --- |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
While we're providing links it might be worth throwing in a mention of the PyAres docs here