# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. """Molecular Designer Env Environment Client.""" from typing import Dict from openenv.core import EnvClient from openenv.core.client_types import StepResult from openenv.core.env_server.types import State from .models import MolecularDesignerEnvAction, MolecularDesignerEnvObservation class MolecularDesignerEnvEnv( EnvClient[MolecularDesignerEnvAction, MolecularDesignerEnvObservation, State] ): """ Client for the Molecular Designer Env Environment. This client maintains a persistent WebSocket connection to the environment server, enabling efficient multi-step interactions with lower latency. Each client instance has its own dedicated environment session on the server. Example: >>> # Connect to a running server >>> with MolecularDesignerEnvEnv(base_url="http://localhost:8000") as client: ... result = client.reset() ... print(result.observation.feedback) ... ... result = client.step(MolecularDesignerEnvAction(smiles="CCO")) ... print(result.observation.feedback) Example with Docker: >>> # Automatically start container and connect >>> client = MolecularDesignerEnvEnv.from_docker_image("molecular_Designer_Env-env:latest") >>> try: ... result = client.reset() ... result = client.step(MolecularDesignerEnvAction(smiles="CC(C)C")) ... finally: ... client.close() """ def _step_payload(self, action: MolecularDesignerEnvAction) -> Dict: """ Convert MolecularDesignerEnvAction to JSON payload for step message. Args: action: MolecularDesignerEnvAction instance Returns: Dictionary representation suitable for JSON encoding """ return { "smiles": action.smiles, } def _parse_result(self, payload: Dict) -> StepResult[MolecularDesignerEnvObservation]: """ Parse server response into StepResult[MolecularDesignerEnvObservation]. Args: payload: JSON response data from server Returns: StepResult with MolecularDesignerEnvObservation """ obs_data = payload.get("observation", {}) observation = MolecularDesignerEnvObservation( is_valid=obs_data.get("is_valid", False), mw=obs_data.get("mw", 0.0), logp=obs_data.get("logp", 0.0), qed=obs_data.get("qed", 0.0), sas=obs_data.get("sas", 0.0), feedback=obs_data.get("feedback", ""), done=payload.get("done", False), reward=payload.get("reward"), metadata=obs_data.get("metadata", {}), ) return StepResult( observation=observation, reward=payload.get("reward"), done=payload.get("done", False), ) def _parse_state(self, payload: Dict) -> State: """ Parse server response into State object. Args: payload: JSON response from state request Returns: State object with episode_id and step_count """ return State( episode_id=payload.get("episode_id"), step_count=payload.get("step_count", 0), )