Subpackages
- biolm.cli package
- biolm.core package
- Subpackages
- Submodules
- biolm.core.asynch module
- biolm.core.auth module
- biolm.core.const module
- biolm.core.expression_evaluator module
- biolm.core.http module
- biolm.core.paths module
- biolm.core.payloads module
- biolm.core.seqflow_auth module
- biolm.core.utils module
- biolm.core.validate module
AAExtendedAAExtendedPlusExtraAAUnambiguousAAUnambiguousEmptyAAUnambiguousPlusExtraDNAUnambiguousPDBSingleOccurrenceOfSingleOrMoreOccurrencesOfaa_extended_validator()aa_unambiguous_validator()dna_unambiguous_validator()empty_or_aa_unambiguous_validator()empty_or_dna_unambiguous_validator()pdb_validator()
- Module contents
- biolm.datasets package
- biolm.hub package
- biolm.io package
- biolm.models package
- biolm.pipeline package
- Submodules
- biolm.pipeline.async_executor module
- biolm.pipeline.base module
- biolm.pipeline.clustering module
- biolm.pipeline.data module
ClusteringStageCofoldingPredictionStageDataPipelineDataPipeline.add_clustering()DataPipeline.add_cofolding_prediction()DataPipeline.add_filter()DataPipeline.add_prediction()DataPipeline.add_predictions()DataPipeline.add_structure_prediction()DataPipeline.explore()DataPipeline.get_merged_results()DataPipeline.plot()DataPipeline.query()DataPipeline.query_results()DataPipeline.stats()
Embed()EmbeddingSpecExtractionSpecFilterStageMatrixExtractionSpecPipelineAPIAuthErrorPredict()PredictionStageSingleStepPipelineStructureSpec
- biolm.pipeline.datastore module
- biolm.pipeline.datastore_duckdb module
DuckDBDataStoreDuckDBDataStore.add_embedding()DuckDBDataStore.add_embeddings_batch()DuckDBDataStore.add_generation_metadata()DuckDBDataStore.add_generation_metadata_batch()DuckDBDataStore.add_prediction()DuckDBDataStore.add_prediction_by_sequence()DuckDBDataStore.add_predictions_batch()DuckDBDataStore.add_sequence()DuckDBDataStore.add_sequences_batch()DuckDBDataStore.add_structure()DuckDBDataStore.close()DuckDBDataStore.count_matching_sequences()DuckDBDataStore.create_pipeline_run()DuckDBDataStore.ensure_input_columns()DuckDBDataStore.execute_filter_sql()DuckDBDataStore.export_to_csv()DuckDBDataStore.export_to_dataframe()DuckDBDataStore.export_to_parquet()DuckDBDataStore.get_all_sequences()DuckDBDataStore.get_column_registry_entry()DuckDBDataStore.get_context()DuckDBDataStore.get_embedding()DuckDBDataStore.get_embeddings_bulk()DuckDBDataStore.get_embeddings_by_sequence()DuckDBDataStore.get_embeddings_concat()DuckDBDataStore.get_existing_input_columns()DuckDBDataStore.get_filter_results()DuckDBDataStore.get_generation_metadata()DuckDBDataStore.get_latest_definition_id()DuckDBDataStore.get_latest_run_id()DuckDBDataStore.get_pipeline_metadata()DuckDBDataStore.get_pipeline_run()DuckDBDataStore.get_predictions()DuckDBDataStore.get_predictions_bulk()DuckDBDataStore.get_predictions_by_sequence()DuckDBDataStore.get_sequence()DuckDBDataStore.get_sequence_attributes_for_ids()DuckDBDataStore.get_sequence_id()DuckDBDataStore.get_sequence_ids_with_prediction()DuckDBDataStore.get_sequences_for_ids()DuckDBDataStore.get_sequences_for_ids_with_columns()DuckDBDataStore.get_stats()DuckDBDataStore.get_structure()DuckDBDataStore.get_structure_by_id()DuckDBDataStore.get_structures_bulk()DuckDBDataStore.get_structures_by_sequence()DuckDBDataStore.get_structures_for_ids()DuckDBDataStore.get_uncached_sequence_ids()DuckDBDataStore.has_prediction()DuckDBDataStore.is_stage_complete()DuckDBDataStore.load_blob()DuckDBDataStore.load_pipeline_definition()DuckDBDataStore.make_filter_ws_name()DuckDBDataStore.mark_stage_complete()DuckDBDataStore.materialize_working_set()DuckDBDataStore.query()DuckDBDataStore.register_column()DuckDBDataStore.save_filter_results()DuckDBDataStore.save_pipeline_definition()DuckDBDataStore.set_context()DuckDBDataStore.set_pipeline_metadata()DuckDBDataStore.store_blob()DuckDBDataStore.store_sequence_attributes()DuckDBDataStore.update_pipeline_run_status()
- biolm.pipeline.filters module
- biolm.pipeline.generative module
DirectGenerationConfigDirectGenerationConfig.item_fieldDirectGenerationConfig.labelDirectGenerationConfig.model_nameDirectGenerationConfig.n_runsDirectGenerationConfig.num_sequencesDirectGenerationConfig.paramsDirectGenerationConfig.sequenceDirectGenerationConfig.structure_columnDirectGenerationConfig.structure_from_modelDirectGenerationConfig.structure_from_stageDirectGenerationConfig.structure_pathDirectGenerationConfig.temperatureDirectGenerationConfig.to_spec()
FoldingEntityGenerate()GenerationConfigGenerationStageGenerativePipelineGenerativePipeline.add_cofolding_prediction()GenerativePipeline.add_filter()GenerativePipeline.add_generation_config()GenerativePipeline.add_prediction()GenerativePipeline.add_predictions()GenerativePipeline.add_stage()GenerativePipeline.replace_generation()GenerativePipeline.run_async()GenerativePipeline.set_generation()GenerativePipeline.use_sequences()
GenerativeProtocolConfigIterativeMaskingDMSConfigIterativeMaskingDMSConfig.actionIterativeMaskingDMSConfig.alphabetIterativeMaskingDMSConfig.batch_sizeIterativeMaskingDMSConfig.exclude_synonymousIterativeMaskingDMSConfig.labelIterativeMaskingDMSConfig.mask_tokenIterativeMaskingDMSConfig.model_nameIterativeMaskingDMSConfig.parent_sequenceIterativeMaskingDMSConfig.positionsIterativeMaskingDMSConfig.roundsIterativeMaskingDMSConfig.to_spec()
SaturationMutagenesisConfigSaturationMutagenesisConfig.alphabetSaturationMutagenesisConfig.ascendingSaturationMutagenesisConfig.batch_sizeSaturationMutagenesisConfig.chainSaturationMutagenesisConfig.exclude_synonymousSaturationMutagenesisConfig.labelSaturationMutagenesisConfig.parent_sequenceSaturationMutagenesisConfig.pdb_strSaturationMutagenesisConfig.positionsSaturationMutagenesisConfig.score_fieldSaturationMutagenesisConfig.scoring_actionSaturationMutagenesisConfig.scoring_modelSaturationMutagenesisConfig.scoring_paramsSaturationMutagenesisConfig.to_spec()SaturationMutagenesisConfig.top_n
ScoringProtocolConfigSequenceSourceConfig
- biolm.pipeline.mlm_remasking module
MLMRemaskerRemaskingConfigRemaskingConfig.actionRemaskingConfig.block_sizeRemaskingConfig.confidence_thresholdRemaskingConfig.conserved_positionsRemaskingConfig.mask_fractionRemaskingConfig.mask_positionsRemaskingConfig.mask_strategyRemaskingConfig.mask_tokenRemaskingConfig.model_nameRemaskingConfig.num_iterationsRemaskingConfig.num_variantsRemaskingConfig.parent_sequenceRemaskingConfig.temperatureRemaskingConfig.to_spec()RemaskingConfig.top_kRemaskingConfig.top_p
create_remasker_from_dict()
- biolm.pipeline.pipeline_def module
- biolm.pipeline.utils module
cif_to_pdb()compute_hamming_distance()compute_sequence_identity()create_run_summary()deduplicate_sequences()export_run_summary()hash_sequence()load_fasta()load_sequences_from_file()load_structure_string()merge_prediction_results()pdb_to_cif()sample_sequences()split_sequences_by_length()summarize_dataframe()validate_sequence()write_fasta()
- biolm.pipeline.visualization module
- Module contents
BasePipelineClusteringResultCofoldingPredictionStageCompositeFilterConservedResidueFilterCustomFilterDataPipelineDataPipeline.add_clustering()DataPipeline.add_cofolding_prediction()DataPipeline.add_filter()DataPipeline.add_prediction()DataPipeline.add_predictions()DataPipeline.add_structure_prediction()DataPipeline.explore()DataPipeline.get_merged_results()DataPipeline.plot()DataPipeline.query()DataPipeline.query_results()DataPipeline.stats()
DataStoreDirectGenerationConfigDirectGenerationConfig.item_fieldDirectGenerationConfig.labelDirectGenerationConfig.model_nameDirectGenerationConfig.n_runsDirectGenerationConfig.num_sequencesDirectGenerationConfig.paramsDirectGenerationConfig.sequenceDirectGenerationConfig.structure_columnDirectGenerationConfig.structure_from_modelDirectGenerationConfig.structure_from_stageDirectGenerationConfig.structure_pathDirectGenerationConfig.temperatureDirectGenerationConfig.to_spec()
DiversityAnalyzerDiversitySamplingFilterDuckDBDataStoreDuckDBDataStore.add_embedding()DuckDBDataStore.add_embeddings_batch()DuckDBDataStore.add_generation_metadata()DuckDBDataStore.add_generation_metadata_batch()DuckDBDataStore.add_prediction()DuckDBDataStore.add_prediction_by_sequence()DuckDBDataStore.add_predictions_batch()DuckDBDataStore.add_sequence()DuckDBDataStore.add_sequences_batch()DuckDBDataStore.add_structure()DuckDBDataStore.close()DuckDBDataStore.count_matching_sequences()DuckDBDataStore.create_pipeline_run()DuckDBDataStore.ensure_input_columns()DuckDBDataStore.execute_filter_sql()DuckDBDataStore.export_to_csv()DuckDBDataStore.export_to_dataframe()DuckDBDataStore.export_to_parquet()DuckDBDataStore.get_all_sequences()DuckDBDataStore.get_column_registry_entry()DuckDBDataStore.get_context()DuckDBDataStore.get_embedding()DuckDBDataStore.get_embeddings_bulk()DuckDBDataStore.get_embeddings_by_sequence()DuckDBDataStore.get_embeddings_concat()DuckDBDataStore.get_existing_input_columns()DuckDBDataStore.get_filter_results()DuckDBDataStore.get_generation_metadata()DuckDBDataStore.get_latest_definition_id()DuckDBDataStore.get_latest_run_id()DuckDBDataStore.get_pipeline_metadata()DuckDBDataStore.get_pipeline_run()DuckDBDataStore.get_predictions()DuckDBDataStore.get_predictions_bulk()DuckDBDataStore.get_predictions_by_sequence()DuckDBDataStore.get_sequence()DuckDBDataStore.get_sequence_attributes_for_ids()DuckDBDataStore.get_sequence_id()DuckDBDataStore.get_sequence_ids_with_prediction()DuckDBDataStore.get_sequences_for_ids()DuckDBDataStore.get_sequences_for_ids_with_columns()DuckDBDataStore.get_stats()DuckDBDataStore.get_structure()DuckDBDataStore.get_structure_by_id()DuckDBDataStore.get_structures_bulk()DuckDBDataStore.get_structures_by_sequence()DuckDBDataStore.get_structures_for_ids()DuckDBDataStore.get_uncached_sequence_ids()DuckDBDataStore.has_prediction()DuckDBDataStore.is_stage_complete()DuckDBDataStore.load_blob()DuckDBDataStore.load_pipeline_definition()DuckDBDataStore.make_filter_ws_name()DuckDBDataStore.mark_stage_complete()DuckDBDataStore.materialize_working_set()DuckDBDataStore.query()DuckDBDataStore.register_column()DuckDBDataStore.save_filter_results()DuckDBDataStore.save_pipeline_definition()DuckDBDataStore.set_context()DuckDBDataStore.set_pipeline_metadata()DuckDBDataStore.store_blob()DuckDBDataStore.store_sequence_attributes()DuckDBDataStore.update_pipeline_run_status()
Embed()EmbeddingSpecExtractionSpecFoldingEntityGenerativePipelineGenerativePipeline.add_cofolding_prediction()GenerativePipeline.add_filter()GenerativePipeline.add_generation_config()GenerativePipeline.add_prediction()GenerativePipeline.add_predictions()GenerativePipeline.add_stage()GenerativePipeline.replace_generation()GenerativePipeline.run_async()GenerativePipeline.set_generation()GenerativePipeline.use_sequences()
GenerativeProtocolConfigHammingDistanceFilterInputSchemaIterativeMaskingDMSConfigIterativeMaskingDMSConfig.actionIterativeMaskingDMSConfig.alphabetIterativeMaskingDMSConfig.batch_sizeIterativeMaskingDMSConfig.exclude_synonymousIterativeMaskingDMSConfig.labelIterativeMaskingDMSConfig.mask_tokenIterativeMaskingDMSConfig.model_nameIterativeMaskingDMSConfig.parent_sequenceIterativeMaskingDMSConfig.positionsIterativeMaskingDMSConfig.roundsIterativeMaskingDMSConfig.to_spec()
MLMRemaskerMatrixExtractionSpecPipelineAPIAuthErrorPipelineContextPipelineMetadataPipelinePlotterPredict()RankingFilterRemaskingConfigRemaskingConfig.actionRemaskingConfig.block_sizeRemaskingConfig.confidence_thresholdRemaskingConfig.conserved_positionsRemaskingConfig.mask_fractionRemaskingConfig.mask_positionsRemaskingConfig.mask_strategyRemaskingConfig.mask_tokenRemaskingConfig.model_nameRemaskingConfig.num_iterationsRemaskingConfig.num_variantsRemaskingConfig.parent_sequenceRemaskingConfig.temperatureRemaskingConfig.to_spec()RemaskingConfig.top_kRemaskingConfig.top_p
SaturationMutagenesisConfigSaturationMutagenesisConfig.alphabetSaturationMutagenesisConfig.ascendingSaturationMutagenesisConfig.batch_sizeSaturationMutagenesisConfig.chainSaturationMutagenesisConfig.exclude_synonymousSaturationMutagenesisConfig.labelSaturationMutagenesisConfig.parent_sequenceSaturationMutagenesisConfig.pdb_strSaturationMutagenesisConfig.positionsSaturationMutagenesisConfig.score_fieldSaturationMutagenesisConfig.scoring_actionSaturationMutagenesisConfig.scoring_modelSaturationMutagenesisConfig.scoring_paramsSaturationMutagenesisConfig.to_spec()SaturationMutagenesisConfig.top_n
ScoringProtocolConfigSequenceClustererSequenceLengthFilterSequenceSourceConfigSingleStepPipelineStageStageResultStructureSpecThresholdFilterValidAminoAcidFilterWorkingSetanalyze_diversity()cif_to_pdb()cluster_sequences()combine_filters()load_structure_string()pdb_to_cif()
- biolm.plugins package
- biolm.protocols package
ProtocolProtocolClientProtocolNotFoundErrorProtocolRunProtocolRunErrorProtocolValidationResultValidationErrorvalidate_protocol_file()ProtocolProtocolValidationResultValidationErrorProtocolValidationResultValidationErrorload_yaml()validate_protocol_file()ProtocolClientProtocolNotFoundErrorProtocolRunProtocolRunErrorLocalRunResultUnsupportedProtocolFeaturecompile_protocol()compile_to_pipeline()run_local_protocol()- Compatibility shims
- biolm.seqframe package
SeqFrameSeqFrame.bioSeqFrame.collect()SeqFrame.columnsSeqFrame.from_csv()SeqFrame.from_dataframe()SeqFrame.from_dataset()SeqFrame.from_fasta()SeqFrame.from_jsonl()SeqFrame.from_protocol()SeqFrame.from_rows()SeqFrame.head()SeqFrame.ioSeqFrame.labSeqFrame.merge_columns()SeqFrame.modelsSeqFrame.protocolsSeqFrame.querySeqFrame.read()SeqFrame.schemaSeqFrame.shapeSeqFrame.to_dataset()SeqFrame.write()
SeqFrameMetadataSeqFrameMetadata.alphabetSeqFrameMetadata.created_bySeqFrameMetadata.extensionsSeqFrameMetadata.from_dict()SeqFrameMetadata.from_parquet_metadata()SeqFrameMetadata.id_columnSeqFrameMetadata.molecule_typeSeqFrameMetadata.sequence_columnSeqFrameMetadata.to_dict()SeqFrameMetadata.to_parquet_metadata()SeqFrameMetadata.version
- biolm.seqframe.core module
SeqFrameSeqFrame.bioSeqFrame.collect()SeqFrame.columnsSeqFrame.from_csv()SeqFrame.from_dataframe()SeqFrame.from_dataset()SeqFrame.from_fasta()SeqFrame.from_jsonl()SeqFrame.from_protocol()SeqFrame.from_rows()SeqFrame.head()SeqFrame.ioSeqFrame.labSeqFrame.merge_columns()SeqFrame.modelsSeqFrame.protocolsSeqFrame.querySeqFrame.read()SeqFrame.schemaSeqFrame.shapeSeqFrame.to_dataset()SeqFrame.write()
- biolm.seqframe.dataset_bridge module
- biolm.seqframe.metadata module
SeqFrameMetadataSeqFrameMetadata.alphabetSeqFrameMetadata.created_bySeqFrameMetadata.extensionsSeqFrameMetadata.from_dict()SeqFrameMetadata.from_parquet_metadata()SeqFrameMetadata.id_columnSeqFrameMetadata.molecule_typeSeqFrameMetadata.sequence_columnSeqFrameMetadata.to_dict()SeqFrameMetadata.to_parquet_metadata()SeqFrameMetadata.version
Submodules
biolm.client module
BioLM convenience client and HTTP client re-exports.
- class biolm.client.AsyncRateLimiter(max_calls: int, period: float)
Bases:
object- limit()
- class biolm.client.BioLM(*, entity: str, action: str, type: str | None = None, items: Any | List[Any], params: dict | None = None, api_key: str | None = None, **kwargs)
Bases:
objectUniversal client for BioLM API.
This is a convenience wrapper that creates a client, makes the request, and returns the result. For long-running operations or when making multiple requests, consider using BioLMApiClient (async) or BioLMApi (sync) directly with proper cleanup via context managers or shutdown().
- Args:
entity (str): The entity name (model, database, calculation, etc). action (str): The action to perform (e.g., ‘generate’, ‘encode’, ‘predict’, ‘search’, ‘finetune’). type (str): The type of item (e.g., ‘sequence’, ‘pdb’, ‘fasta_str’). item (Union[Any, List[Any]]): The item(s) to process. params (Optional[dict]): Optional parameters for the action. raise_httpx (bool): Whether to raise HTTPX errors. stop_on_error (bool): Stop on first error if True. output (str): ‘memory’ or ‘disk’. file_path (Optional[str]): Output file path if output=’disk’. api_key (Optional[str]): API key for authentication. compress_requests (bool): Enable gzip compression for POST requests. Default: True. compress_threshold (int): Minimum payload size in bytes to trigger compression. Default: 256.
- run() → Any
Run the specified action on the entity with the given item(s).
- biolm.client.BioLMApi
alias of
BlockingBioLMApi
- class biolm.client.BioLMApiClient(model_name: str, api_key: str | None = None, base_url: str | None = None, timeout: Timeout = Timeout(connect=10.0, read=1200, write=1200, pool=1200), raise_httpx: bool = False, unwrap_single: bool = True, semaphore: int | Semaphore | None = 16, rate_limit: str | None = None, retry_error_batches: bool = True, compress_requests: bool = True, compress_threshold: int = 256, concurrent_batches: bool = True, http2: bool = True)
Bases:
object- async call(func: str, items: List[dict], params: dict | None = None, raw: bool = False)
- encode(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True, progress_callback: Callable[[int, int], None] | None = None)
- static extract_max_items(schema: dict) → int | None
Extracts the ‘maxItems’ value for the ‘items’ key from the schema. Returns the integer value if found, else None.
- generate(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True, progress_callback: Callable[[int, int], None] | None = None)
- async lookup(query: dict | List[dict], *, raw: bool = False, output: str = 'memory', file_path: str | None = None)
- predict(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True, progress_callback: Callable[[int, int], None] | None = None)
- async schema(model: str, action: str) → dict | None
Fetch the JSON schema for a given model and action, with caching. Returns the schema dict if successful, else None. Uses a module-level cache keyed by (model, action) so it is safe to use from any event loop (sync wrapper, async tests, pytest-xdist workers).
Schema is always fetched from the hosted platform API without credentials. Hub gateways and custom model API hosts may not expose /schema/, and sending API tokens to the public schema endpoint can return 401.
- score(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True)
- search(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True)
- async shutdown()
- class biolm.client.CredentialsProvider
Bases:
object- static get_auth_headers(api_key: str | None = None) → Dict[str, str]
- biolm.client.batch_iterable(iterable, batch_size)
- biolm.client.is_list_of_lists(items, check_n=10)
- biolm.client.parse_rate_limit(rate: str)
biolm.finetune module
Programmatic finetuning client for BioLM.
Wraps the /api/finetune/ endpoints (the SDK-facing companion to the browser
console finetuning UI) so callers can launch and track XGBoost and DSM
finetuning runs from Python without a session cookie.
Auth follows the same rules as the rest of the SDK: pass api_key= or set
BIOLM_TOKEN (see biolm.core.http.CredentialsProvider).
- class biolm.finetune.Finetune
Bases:
objectLaunch and track BioLM finetuning runs.
All methods are classmethods returning plain dicts.
*_dataarguments accept a list of row dicts ([{"sequence": ..., "label": ...}, ...]) or a raw CSV string; they are sent inline as JSON.- classmethod cancel(run_id: str, **kwargs) → dict
Synchronous wrapper for
cancel_async().
- async classmethod cancel_async(run_id: str, *, api_key: str | None = None, base_url: str | None = None) → dict
Cancel an in-flight run.
- classmethod dsm_rl(**kwargs) → dict
Synchronous wrapper for
dsm_rl_async().
- async classmethod dsm_rl_async(*, seed_sequences: List[str] | str, oracle_type: str = 'esmc', stability_objective: str = 'thermostability', training_mode: str = 'online', algorithm: str = 'ppo', num_episodes: int = 100, samples_per_episode: int = 64, learning_rate: float = 0.0003, batch_size: int = 8, mask_ratio: float = 0.3, mutation_rate: float = 0.1, run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch DSM RL protein optimization against an oracle.
- classmethod dsm_stage1(**kwargs) → dict
Synchronous wrapper for
dsm_stage1_async().
- async classmethod dsm_stage1_async(*, train_data: List[Dict[str, Any]] | str, test_data: List[Dict[str, Any]] | str | None = None, valid_data: List[Dict[str, Any]] | str | None = None, sequence_col: str = 'sequence', lr: float = 0.0001, batch_size: int = 8, grad_accum: int = 16, max_steps: int = 50000, max_length: int = 2048, save_every: int = 1000, fp16: bool = False, run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch DSM Stage 1 (single-chain masked-LM finetune).
- classmethod dsm_stage2(**kwargs) → dict
Synchronous wrapper for
dsm_stage2_async().
- async classmethod dsm_stage2_async(*, stage1_checkpoint: str, paired_data: List[Dict[str, Any]] | str, unpaired_data: List[Dict[str, Any]] | str | None = None, heavy_col: str = 'heavy', light_col: str = 'light', use_mixed_training: bool = False, fp16: bool = False, lr: float = 5e-05, batch_size: int = 4, unpaired_batch_size: int = 8, grad_accum: int = 16, max_steps: int = 25000, max_length: int = 300, unpaired_ratio: float = 2.0, run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch DSM Stage 2 (paired multichain finetune from a Stage 1 checkpoint).
- classmethod get_run(run_id: str, **kwargs) → dict
Synchronous wrapper for
get_run_async().
- async classmethod get_run_async(run_id: str, *, api_key: str | None = None, base_url: str | None = None) → dict
Fetch sanitized detail (status, results) for a single run.
- classmethod list_runs(**kwargs) → dict
Synchronous wrapper for
list_runs_async().
- async classmethod list_runs_async(*, dag: str | None = None, status: str | None = None, page: int = 1, page_size: int = 20, api_key: str | None = None, base_url: str | None = None) → dict
List the caller’s finetune runs (paginated).
- classmethod progress(run_id: str, **kwargs) → dict
Synchronous wrapper for
progress_async().
- async classmethod progress_async(run_id: str, *, api_key: str | None = None, base_url: str | None = None) → dict
Fetch lightweight status + telemetry channel id for a run.
- classmethod wait(run_id: str, *, poll_interval: float = 15.0, timeout: float | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Block until run_id reaches a terminal state, returning its detail.
- classmethod xgboost(**kwargs) → dict
Synchronous wrapper for
xgboost_async().
- async classmethod xgboost_async(*, train_data: List[Dict[str, Any]] | str, embedding_models: List[str], task_type: str = 'classification', target_column: str = 'label', text_column: str = 'sequence', test_data: List[Dict[str, Any]] | str | None = None, validation_data: List[Dict[str, Any]] | str | None = None, n_estimators: int = 100, max_depth: int = 6, learning_rate: float = 0.1, n_splits: int = 5, seed: int = 42, hyperopt: bool = False, hyperopt_n_trials: int | None = None, antibody_mode: bool = False, heavy_column: str = 'heavy', light_column: str = 'light', modality: str = 'protein', run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch an XGBoost finetune (optionally with Ray Tune hyperopt).
biolm.platform module
Platform management client for BioLM console APIs.
Talks to {BIOLM_BASE_DOMAIN}/console/api/ with a persistent httpx.Client
so Django session cookies survive account-context switches. A workspace is an
account + environment pair.
- exception biolm.platform.AmbiguousOrganizationError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorMore than one organization matched the requested identifier.
- exception biolm.platform.AmbiguousWorkspaceError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorMore than one workspace matched the requested path.
- exception biolm.platform.OrganizationNotFoundError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorNo organization matched the requested identifier.
- class biolm.platform.PlatformClient(api_key: str | None = None, base_url: str | None = None, timeout: float = 30.0, transport: BaseTransport | None = None, client: Client | None = None)
Bases:
objectSync client for BioLM platform (orgs, environments, budgets, workspaces).
Instances retain session cookies and active account context. They are stateful, session-scoped, and not safe for concurrent use across threads.
- close() → None
- create_api_key(account: str | None = None) → Dict[str, str]
Create an API key and return its one-time secret.
The key is owned by the active server-side account context. Pass
account(an org slug or the personal label) to create the key under a different account; the switch and creation happen in this one session so organization ownership cannot silently fall back to personal. The original context is restored afterward. The returnedtokenis shown only once and is not stored by the SDK.
- create_environment(name: str) → Dict[str, Any]
- create_organization(name: str, slug: str) → Dict[str, Any]
- create_workspace(name: str, account: str | None = None) → Workspace
- current_workspace() → Workspace
- delete_api_key(token_or_prefix: str) → None
Revoke an API key by full token or eight-character prefix.
- get_budget() → Dict[str, Any]
- get_context() → Dict[str, Any]
- get_current_user() → Dict[str, Any]
- get_organization(identifier: int | str) → Dict[str, Any]
- get_usage_summary(year: int | None = None, month: int | None = None, environment_id: int | None = None, account: str | None = None) → Dict[str, Any]
Return monthly usage for the current or named account.
- get_workspace(path: str) → Workspace
Resolve and return the workspace matching an exact path.
- invite_to_organization(identifier: int | str, email: str, role: str = 'member') → Dict[str, Any]
- list_environments() → List[Dict[str, Any]]
- list_organizations() → List[Dict[str, Any]]
- list_workspaces() → List[Workspace]
List personal and organization workspaces, restoring prior context.
The environments endpoint is session-scoped, so enumeration must switch the backend account context for each account. Those switches may cause the backend to ensure or select a default environment; there is no context-free environment listing endpoint available.
- set_budget(workspace_budget: float) → Dict[str, Any]
- set_context(account_type: str, account_id: int | None = None, environment_id: int | None = None) → Dict[str, Any]
- exception biolm.platform.PlatformError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
ExceptionRaised when a console API request fails or returns an error status.
- class biolm.platform.Workspace(account_type: str, account_id: int, environment_id: int, account: str, environment: str)
Bases:
objectImmutable account + environment pair.
account/environmentare path segments (org slug or personal label, and environment slug from the APInamefield). IDs remain authoritative.- account: str
- account_id: int
- account_type: str
- environment: str
- environment_id: int
- property path: str
- exception biolm.platform.WorkspaceNotFoundError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorNo workspace matched the requested path.
biolm.progress module
Shared Rich progress UI for batch operations. Used by CLI and Model (progress=True).
- biolm.progress.rich_progress(total_items: int, description: str = 'Processing...', console: Any | None = None)
Context manager that yields a progress callback for batch operations.
The callback has signature (completed: int, total: int) -> None. Call it after each batch with the number of items completed so far and total items. Uses Rich Progress (spinner, bar, task progress) when Rich is available; otherwise yields a no-op callback.
- Args:
total_items: Total number of items to process. description: Description shown in the progress bar. console: Rich Console instance (default: new Console()).
- Yields:
A callable (completed: int, total: int) -> None to update progress.
biolm.protocol_runs module (compat shim)
Re-exports biolm.protocols.runs. Prefer from biolm.protocols import ProtocolClient.
Backward compatibility shim — use biolm.protocols.runs instead.
biolm.protocols package
See biolm.protocols package for submodules (model, validation, runs, runtime).
BioLM Protocols — validation, hosted runs, and local execution.
- class biolm.protocols.Protocol(yaml_path: str)
Bases:
objectLoad and validate BioLM protocol YAML files.
- Args:
- yaml_path: Path to a protocol YAML file. The file is loaded and
validated on construction; invalid YAML raises
ValueError.
Use
validate()as a classmethod to validate without instantiating.- execute(inputs: Dict[str, Any] | None = None)
Execute protocol locally with given inputs.
- Args:
inputs: Input values for the protocol (optional, uses defaults from protocol if not provided).
- Returns:
biolm.protocols.runtime.LocalRunResultwith dataframe, records, and metadata.- Requires:
biolm[pipeline]optional dependencies.
- classmethod fetch_by_id(protocol_id: str, api_key: str | None = None, base_url: str | None = None) → dict
Fetch a protocol from the platform by ID (synchronous wrapper).
- Args:
protocol_id: Protocol ID to fetch api_key: Optional API key for authentication base_url: Optional base URL (defaults to BIOLMAI_BASE_API_URL)
- Returns:
Protocol data as dict (same structure as YAML)
- Raises:
FileNotFoundError: If protocol not found (404) PermissionError: If not authenticated (401) ValueError: If API request fails
- async classmethod fetch_by_id_async(protocol_id: str, api_key: str | None = None, base_url: str | None = None) → dict
Fetch a protocol from the platform by ID.
- Args:
protocol_id: Protocol ID to fetch api_key: Optional API key for authentication base_url: Optional base URL (defaults to BIOLMAI_BASE_API_URL)
- Returns:
Protocol data as dict (same structure as YAML)
- Raises:
FileNotFoundError: If protocol not found (404) PermissionError: If not authenticated (401) ValueError: If API request fails
- classmethod init(output_path: str, example: str | None = None, force: bool = False) → str
Initialize a new protocol YAML file.
- Args:
output_path: Path where the protocol file should be created example: Optional example template name to use force: If True, overwrite existing file
- Returns:
Path to the created file
- Raises:
FileExistsError: If file exists and force=False ValueError: If example name is invalid FileNotFoundError: If example file doesn’t exist
- static render_report(protocol_data: dict, source: str = 'file', console=None) → None
Render a formatted report of the protocol using Rich.
- Args:
protocol_data: Protocol data dictionary source: Source description (e.g., “file”, “platform”) console: Optional Rich Console instance (creates one if not provided)
- Raises:
ValueError: If protocol_data is invalid or missing required fields
- classmethod validate(yaml_path: str) → ProtocolValidationResult
Validate a protocol YAML file.
- class biolm.protocols.ProtocolClient(api_key: str | None = None, base_url: str | None = None)
Bases:
objectSubmit and monitor BioLM protocol runs from Python.
Wraps the
/api/protocols/REST endpoints. Usesubmit()to start a run,run_and_wait()for a blocking workflow, orget_run()to poll an existing run ID.- get(slug: str, version: int | None = None) → Dict[str, Any]
- get_run(run_id: str) → ProtocolRun
Reconnect to an existing run by ID.
- list(search: str | None = None, page: int = 1, page_size: int = 20) → Dict[str, Any]
- run_and_wait(slug: str, inputs: Dict[str, Any], run_name: str | None = None, timeout: float = 3600.0, show_progress: bool = True, poll_interval: float = 5.0) → Dict[str, Any]
- submit(slug: str, inputs: Dict[str, Any], version: int | None = None, run_name: str | None = None, environment_id: int | None = None, files: Dict[str, Any] | None = None) → ProtocolRun
- exception biolm.protocols.ProtocolNotFoundError
Bases:
ProtocolRunErrorThe requested protocol slug/version does not exist or is not accessible.
- class biolm.protocols.ProtocolRun(data: Dict[str, Any], client: ProtocolClient)
Bases:
objectA submitted protocol run returned by
ProtocolClient.submit().- cancel() → Dict[str, Any]
Cancel this run (idempotent; may error if already terminal).
- download(output_dir: str | Path = '.', file_type: str = 'csv', overwrite: bool = False) → Path
- download_files(*, output_dir: str | Path = '.', file_type: str = 'csv', overwrite: bool = False) → Path
Compatibility alias for
download().
- progress() → Dict[str, Any]
- refresh() → ProtocolRun
- results() → Dict[str, Any]
- to_dataframe(*, output_dir: str | Path = '.', overwrite: bool = False)
Download CSV zip and return a pandas DataFrame.
- wait(timeout: float = 3600.0, show_progress: bool = True, poll_interval: float = 5.0) → ProtocolRun
Block until this run reaches a terminal state.
Waiting is websocket-first: it connects to the run’s telemetry channel for live progress. If the
websocketsdependency is missing, the connection fails, or the stream closes while the run is still nonterminal, it transparently falls back to REST polling of the run detail endpoint until the run succeeds, fails, or is cancelled.- Parameters:
timeout – Total deadline in seconds shared across the websocket and REST polling phases. The deadline is not reset after a websocket failure.
show_progress – Print status changes to stdout.
poll_interval – Seconds between REST polls during fallback. Each sleep is clamped to the remaining deadline and must be greater than zero.
- Returns:
selffor chaining.- Raises:
ProtocolRunError – If the run fails or is cancelled.
TimeoutError – If the total deadline elapses before completion.
ValueError – If
poll_intervalis not greater than zero.
- exception biolm.protocols.ProtocolRunError
Bases:
ExceptionA protocol run failed, was cancelled, or the API returned an error.
- class biolm.protocols.ProtocolValidationResult(is_valid: bool, errors: ~typing.List[~biolm.protocols.validation.ValidationError] = <factory>, warnings: ~typing.List[str] = <factory>, statistics: ~typing.Dict[str, ~typing.Any] = <factory>)
Bases:
objectResult of protocol validation.
- add_error(message: str, path: str = '', error_type: str = 'unknown')
- add_warning(message: str)
- errors: List[ValidationError]
- is_valid: bool
- statistics: Dict[str, Any]
- warnings: List[str]
- class biolm.protocols.ValidationError(message: str, path: str = '', error_type: str = 'unknown')
Bases:
objectRepresents a single validation error.
- error_type: str = 'unknown'
- message: str
- path: str = ''
- biolm.protocols.validate_protocol_file(yaml_path: str) → ProtocolValidationResult
Validate a protocol YAML file.
biolm.protocol_runtime module (compat shim)
Re-exports biolm.protocols.runtime. Prefer from biolm.protocols.runtime import run_local_protocol.
Backward compatibility shim — use biolm.protocols.runtime instead.
biolm.volumes module
Deprecated compatibility placeholder for BioLM runtime volumes.
- class biolm.volumes.Volume(name: str | None = None, api_key: str | None = None)
Bases:
objectDeprecated placeholder retained for constructor and import compatibility.
- Args:
name: Legacy volume name. api_key: Legacy API token argument.
- create(name: str, **kwargs)
Reject direct local volume creation.
- delete(name: str | None = None) → bool
Reject direct local volume deletion.
- get(name: str | None = None)
Reject direct local volume lookup.
- list()
Reject direct local volume listing.
biolm.workspaces module
Workspace management for BioLM.
The workspace identity is an account + environment pair. Prefer
biolm.platform.PlatformClient for listing, switching, and creating
workspaces. This module re-exports the public types for compatibility.
- exception biolm.workspaces.AmbiguousWorkspaceError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorMore than one workspace matched the requested path.
- class biolm.workspaces.PlatformClient(api_key: str | None = None, base_url: str | None = None, timeout: float = 30.0, transport: BaseTransport | None = None, client: Client | None = None)
Bases:
objectSync client for BioLM platform (orgs, environments, budgets, workspaces).
Instances retain session cookies and active account context. They are stateful, session-scoped, and not safe for concurrent use across threads.
- close() → None
- create_api_key(account: str | None = None) → Dict[str, str]
Create an API key and return its one-time secret.
The key is owned by the active server-side account context. Pass
account(an org slug or the personal label) to create the key under a different account; the switch and creation happen in this one session so organization ownership cannot silently fall back to personal. The original context is restored afterward. The returnedtokenis shown only once and is not stored by the SDK.
- create_environment(name: str) → Dict[str, Any]
- create_organization(name: str, slug: str) → Dict[str, Any]
- create_workspace(name: str, account: str | None = None) → Workspace
- current_workspace() → Workspace
- delete_api_key(token_or_prefix: str) → None
Revoke an API key by full token or eight-character prefix.
- get_budget() → Dict[str, Any]
- get_context() → Dict[str, Any]
- get_current_user() → Dict[str, Any]
- get_organization(identifier: int | str) → Dict[str, Any]
- get_usage_summary(year: int | None = None, month: int | None = None, environment_id: int | None = None, account: str | None = None) → Dict[str, Any]
Return monthly usage for the current or named account.
- get_workspace(path: str) → Workspace
Resolve and return the workspace matching an exact path.
- invite_to_organization(identifier: int | str, email: str, role: str = 'member') → Dict[str, Any]
- list_environments() → List[Dict[str, Any]]
- list_organizations() → List[Dict[str, Any]]
- list_workspaces() → List[Workspace]
List personal and organization workspaces, restoring prior context.
The environments endpoint is session-scoped, so enumeration must switch the backend account context for each account. Those switches may cause the backend to ensure or select a default environment; there is no context-free environment listing endpoint available.
- set_budget(workspace_budget: float) → Dict[str, Any]
- set_context(account_type: str, account_id: int | None = None, environment_id: int | None = None) → Dict[str, Any]
- exception biolm.workspaces.PlatformError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
ExceptionRaised when a console API request fails or returns an error status.
- class biolm.workspaces.Workspace(account_type: str, account_id: int, environment_id: int, account: str, environment: str)
Bases:
objectImmutable account + environment pair.
account/environmentare path segments (org slug or personal label, and environment slug from the APInamefield). IDs remain authoritative.- account: str
- account_id: int
- account_type: str
- environment: str
- environment_id: int
- property path: str
- exception biolm.workspaces.WorkspaceNotFoundError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorNo workspace matched the requested path.
Module contents
Top-level package for BioLM.
- exception biolm.AmbiguousWorkspaceError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorMore than one workspace matched the requested path.
- class biolm.BioLM(*, entity: str, action: str, type: str | None = None, items: Any | List[Any], params: dict | None = None, api_key: str | None = None, **kwargs)
Bases:
objectUniversal client for BioLM API.
This is a convenience wrapper that creates a client, makes the request, and returns the result. For long-running operations or when making multiple requests, consider using BioLMApiClient (async) or BioLMApi (sync) directly with proper cleanup via context managers or shutdown().
- Args:
entity (str): The entity name (model, database, calculation, etc). action (str): The action to perform (e.g., ‘generate’, ‘encode’, ‘predict’, ‘search’, ‘finetune’). type (str): The type of item (e.g., ‘sequence’, ‘pdb’, ‘fasta_str’). item (Union[Any, List[Any]]): The item(s) to process. params (Optional[dict]): Optional parameters for the action. raise_httpx (bool): Whether to raise HTTPX errors. stop_on_error (bool): Stop on first error if True. output (str): ‘memory’ or ‘disk’. file_path (Optional[str]): Output file path if output=’disk’. api_key (Optional[str]): API key for authentication. compress_requests (bool): Enable gzip compression for POST requests. Default: True. compress_threshold (int): Minimum payload size in bytes to trigger compression. Default: 256.
- run() → Any
Run the specified action on the entity with the given item(s).
- biolm.BioLMApi
alias of
BlockingBioLMApi
- class biolm.BioLMApiClient(model_name: str, api_key: str | None = None, base_url: str | None = None, timeout: Timeout = Timeout(connect=10.0, read=1200, write=1200, pool=1200), raise_httpx: bool = False, unwrap_single: bool = True, semaphore: int | Semaphore | None = 16, rate_limit: str | None = None, retry_error_batches: bool = True, compress_requests: bool = True, compress_threshold: int = 256, concurrent_batches: bool = True, http2: bool = True)
Bases:
object- async call(func: str, items: List[dict], params: dict | None = None, raw: bool = False)
- encode(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True, progress_callback: Callable[[int, int], None] | None = None)
- static extract_max_items(schema: dict) → int | None
Extracts the ‘maxItems’ value for the ‘items’ key from the schema. Returns the integer value if found, else None.
- generate(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True, progress_callback: Callable[[int, int], None] | None = None)
- async lookup(query: dict | List[dict], *, raw: bool = False, output: str = 'memory', file_path: str | None = None)
- predict(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True, progress_callback: Callable[[int, int], None] | None = None)
- async schema(model: str, action: str) → dict | None
Fetch the JSON schema for a given model and action, with caching. Returns the schema dict if successful, else None. Uses a module-level cache keyed by (model, action) so it is safe to use from any event loop (sync wrapper, async tests, pytest-xdist workers).
Schema is always fetched from the hosted platform API without credentials. Hub gateways and custom model API hosts may not expose /schema/, and sending API tokens to the public schema endpoint can return 401.
- score(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True)
- search(*, items: List[dict], params: dict | None = None, stop_on_error: bool = False, output: str = 'memory', file_path: str | None = None, overwrite: bool = True)
- async shutdown()
- class biolm.Finetune
Bases:
objectLaunch and track BioLM finetuning runs.
All methods are classmethods returning plain dicts.
*_dataarguments accept a list of row dicts ([{"sequence": ..., "label": ...}, ...]) or a raw CSV string; they are sent inline as JSON.- classmethod cancel(run_id: str, **kwargs) → dict
Synchronous wrapper for
cancel_async().
- async classmethod cancel_async(run_id: str, *, api_key: str | None = None, base_url: str | None = None) → dict
Cancel an in-flight run.
- classmethod dsm_rl(**kwargs) → dict
Synchronous wrapper for
dsm_rl_async().
- async classmethod dsm_rl_async(*, seed_sequences: List[str] | str, oracle_type: str = 'esmc', stability_objective: str = 'thermostability', training_mode: str = 'online', algorithm: str = 'ppo', num_episodes: int = 100, samples_per_episode: int = 64, learning_rate: float = 0.0003, batch_size: int = 8, mask_ratio: float = 0.3, mutation_rate: float = 0.1, run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch DSM RL protein optimization against an oracle.
- classmethod dsm_stage1(**kwargs) → dict
Synchronous wrapper for
dsm_stage1_async().
- async classmethod dsm_stage1_async(*, train_data: List[Dict[str, Any]] | str, test_data: List[Dict[str, Any]] | str | None = None, valid_data: List[Dict[str, Any]] | str | None = None, sequence_col: str = 'sequence', lr: float = 0.0001, batch_size: int = 8, grad_accum: int = 16, max_steps: int = 50000, max_length: int = 2048, save_every: int = 1000, fp16: bool = False, run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch DSM Stage 1 (single-chain masked-LM finetune).
- classmethod dsm_stage2(**kwargs) → dict
Synchronous wrapper for
dsm_stage2_async().
- async classmethod dsm_stage2_async(*, stage1_checkpoint: str, paired_data: List[Dict[str, Any]] | str, unpaired_data: List[Dict[str, Any]] | str | None = None, heavy_col: str = 'heavy', light_col: str = 'light', use_mixed_training: bool = False, fp16: bool = False, lr: float = 5e-05, batch_size: int = 4, unpaired_batch_size: int = 8, grad_accum: int = 16, max_steps: int = 25000, max_length: int = 300, unpaired_ratio: float = 2.0, run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch DSM Stage 2 (paired multichain finetune from a Stage 1 checkpoint).
- classmethod get_run(run_id: str, **kwargs) → dict
Synchronous wrapper for
get_run_async().
- async classmethod get_run_async(run_id: str, *, api_key: str | None = None, base_url: str | None = None) → dict
Fetch sanitized detail (status, results) for a single run.
- classmethod list_runs(**kwargs) → dict
Synchronous wrapper for
list_runs_async().
- async classmethod list_runs_async(*, dag: str | None = None, status: str | None = None, page: int = 1, page_size: int = 20, api_key: str | None = None, base_url: str | None = None) → dict
List the caller’s finetune runs (paginated).
- classmethod progress(run_id: str, **kwargs) → dict
Synchronous wrapper for
progress_async().
- async classmethod progress_async(run_id: str, *, api_key: str | None = None, base_url: str | None = None) → dict
Fetch lightweight status + telemetry channel id for a run.
- classmethod wait(run_id: str, *, poll_interval: float = 15.0, timeout: float | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Block until run_id reaches a terminal state, returning its detail.
- classmethod xgboost(**kwargs) → dict
Synchronous wrapper for
xgboost_async().
- async classmethod xgboost_async(*, train_data: List[Dict[str, Any]] | str, embedding_models: List[str], task_type: str = 'classification', target_column: str = 'label', text_column: str = 'sequence', test_data: List[Dict[str, Any]] | str | None = None, validation_data: List[Dict[str, Any]] | str | None = None, n_estimators: int = 100, max_depth: int = 6, learning_rate: float = 0.1, n_splits: int = 5, seed: int = 42, hyperopt: bool = False, hyperopt_n_trials: int | None = None, antibody_mode: bool = False, heavy_column: str = 'heavy', light_column: str = 'light', modality: str = 'protein', run_name: str | None = None, environment_id: int | str | None = None, api_key: str | None = None, base_url: str | None = None) → dict
Launch an XGBoost finetune (optionally with Ray Tune hyperopt).
- class biolm.Model(name: str, api_key: str | None = None, **kwargs)
Bases:
objectUser-friendly model interface for BioLM API.
- Args:
name (str): The model name (e.g., ‘esm2-8m’, ‘esmfold’). api_key (Optional[str]): API key for authentication.
**kwargs: Additional arguments passed to BioLMApi.
- encode(items: Any | List[Any], type: str | None = None, params: dict | None = None, progress: bool = True, progress_callback: Callable[[int, int], None] | None = None, **kwargs)
Encode using the model.
- Args:
items: Single item or list of items to encode. type: Type of item (e.g., ‘sequence’). Required if items are not dicts. params: Optional parameters for the encoding. progress: If True (default), show Rich progress bar (multiple items only). progress_callback: Optional (completed, total) callback; overrides progress=True if provided.
**kwargs: Additional arguments (stop_on_error, output, file_path, etc.).- Returns:
Encoding results.
- generate(items: Any | List[Any], type: str | None = None, params: dict | None = None, progress: bool = True, progress_callback: Callable[[int, int], None] | None = None, **kwargs)
Generate using the model.
- Args:
items: Single item or list of items to generate from. type: Type of item (e.g., ‘context’, ‘pdb’). Required if items are not dicts. params: Optional parameters for the generation. progress: If True (default), show Rich progress bar (multiple items only). progress_callback: Optional (completed, total) callback; overrides progress=True if provided.
**kwargs: Additional arguments (stop_on_error, output, file_path, etc.).- Returns:
Generation results.
- get_example(action: str | None = None, format: str = 'python', **kwargs) → str
Get SDK usage example for this model.
- Args:
action: Action name (encode, predict, generate, lookup). If None, generates for first available action. format: Output format (‘python’, ‘markdown’, ‘rst’, ‘json’).
**kwargs: Additional arguments passed to ExampleGenerator (base_url).- Returns:
Formatted example string.
- get_examples(format: str = 'python', **kwargs) → str
Get SDK usage examples for all supported actions of this model.
- Args:
format: Output format (‘python’, ‘markdown’, ‘rst’, ‘json’).
**kwargs: Additional arguments passed to ExampleGenerator (base_url).- Returns:
Formatted examples string with all actions.
- lookup(query: dict | List[dict], **kwargs)
Lookup using the model.
- Args:
query: Query dict or list of query dicts.
**kwargs: Additional arguments (raw, output, file_path).- Returns:
Lookup results.
- predict(items: Any | List[Any], type: str | None = None, params: dict | None = None, progress: bool = True, progress_callback: Callable[[int, int], None] | None = None, **kwargs)
Predict using the model.
- Args:
items: Single item or list of items to predict. type: Type of item (e.g., ‘sequence’, ‘pdb’). Required if items are not dicts. params: Optional parameters for the prediction. progress: If True (default), show Rich progress bar (multiple items only). progress_callback: Optional (completed, total) callback; overrides progress=True if provided.
**kwargs: Additional arguments (stop_on_error, output, file_path, etc.).- Returns:
Prediction results.
- class biolm.PlatformClient(api_key: str | None = None, base_url: str | None = None, timeout: float = 30.0, transport: BaseTransport | None = None, client: Client | None = None)
Bases:
objectSync client for BioLM platform (orgs, environments, budgets, workspaces).
Instances retain session cookies and active account context. They are stateful, session-scoped, and not safe for concurrent use across threads.
- close() → None
- create_api_key(account: str | None = None) → Dict[str, str]
Create an API key and return its one-time secret.
The key is owned by the active server-side account context. Pass
account(an org slug or the personal label) to create the key under a different account; the switch and creation happen in this one session so organization ownership cannot silently fall back to personal. The original context is restored afterward. The returnedtokenis shown only once and is not stored by the SDK.
- create_environment(name: str) → Dict[str, Any]
- create_organization(name: str, slug: str) → Dict[str, Any]
- create_workspace(name: str, account: str | None = None) → Workspace
- current_workspace() → Workspace
- delete_api_key(token_or_prefix: str) → None
Revoke an API key by full token or eight-character prefix.
- get_budget() → Dict[str, Any]
- get_context() → Dict[str, Any]
- get_current_user() → Dict[str, Any]
- get_organization(identifier: int | str) → Dict[str, Any]
- get_usage_summary(year: int | None = None, month: int | None = None, environment_id: int | None = None, account: str | None = None) → Dict[str, Any]
Return monthly usage for the current or named account.
- get_workspace(path: str) → Workspace
Resolve and return the workspace matching an exact path.
- invite_to_organization(identifier: int | str, email: str, role: str = 'member') → Dict[str, Any]
- list_environments() → List[Dict[str, Any]]
- list_organizations() → List[Dict[str, Any]]
- list_workspaces() → List[Workspace]
List personal and organization workspaces, restoring prior context.
The environments endpoint is session-scoped, so enumeration must switch the backend account context for each account. Those switches may cause the backend to ensure or select a default environment; there is no context-free environment listing endpoint available.
- set_budget(workspace_budget: float) → Dict[str, Any]
- set_context(account_type: str, account_id: int | None = None, environment_id: int | None = None) → Dict[str, Any]
- exception biolm.PlatformError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
ExceptionRaised when a console API request fails or returns an error status.
- class biolm.Protocol(yaml_path: str)
Bases:
objectLoad and validate BioLM protocol YAML files.
- Args:
- yaml_path: Path to a protocol YAML file. The file is loaded and
validated on construction; invalid YAML raises
ValueError.
Use
validate()as a classmethod to validate without instantiating.- execute(inputs: Dict[str, Any] | None = None)
Execute protocol locally with given inputs.
- Args:
inputs: Input values for the protocol (optional, uses defaults from protocol if not provided).
- Returns:
biolm.protocols.runtime.LocalRunResultwith dataframe, records, and metadata.- Requires:
biolm[pipeline]optional dependencies.
- classmethod fetch_by_id(protocol_id: str, api_key: str | None = None, base_url: str | None = None) → dict
Fetch a protocol from the platform by ID (synchronous wrapper).
- Args:
protocol_id: Protocol ID to fetch api_key: Optional API key for authentication base_url: Optional base URL (defaults to BIOLMAI_BASE_API_URL)
- Returns:
Protocol data as dict (same structure as YAML)
- Raises:
FileNotFoundError: If protocol not found (404) PermissionError: If not authenticated (401) ValueError: If API request fails
- async classmethod fetch_by_id_async(protocol_id: str, api_key: str | None = None, base_url: str | None = None) → dict
Fetch a protocol from the platform by ID.
- Args:
protocol_id: Protocol ID to fetch api_key: Optional API key for authentication base_url: Optional base URL (defaults to BIOLMAI_BASE_API_URL)
- Returns:
Protocol data as dict (same structure as YAML)
- Raises:
FileNotFoundError: If protocol not found (404) PermissionError: If not authenticated (401) ValueError: If API request fails
- classmethod init(output_path: str, example: str | None = None, force: bool = False) → str
Initialize a new protocol YAML file.
- Args:
output_path: Path where the protocol file should be created example: Optional example template name to use force: If True, overwrite existing file
- Returns:
Path to the created file
- Raises:
FileExistsError: If file exists and force=False ValueError: If example name is invalid FileNotFoundError: If example file doesn’t exist
- static render_report(protocol_data: dict, source: str = 'file', console=None) → None
Render a formatted report of the protocol using Rich.
- Args:
protocol_data: Protocol data dictionary source: Source description (e.g., “file”, “platform”) console: Optional Rich Console instance (creates one if not provided)
- Raises:
ValueError: If protocol_data is invalid or missing required fields
- classmethod validate(yaml_path: str) → ProtocolValidationResult
Validate a protocol YAML file.
- class biolm.ProtocolClient(api_key: str | None = None, base_url: str | None = None)
Bases:
objectSubmit and monitor BioLM protocol runs from Python.
Wraps the
/api/protocols/REST endpoints. Usesubmit()to start a run,run_and_wait()for a blocking workflow, orget_run()to poll an existing run ID.- get(slug: str, version: int | None = None) → Dict[str, Any]
- get_run(run_id: str) → ProtocolRun
Reconnect to an existing run by ID.
- list(search: str | None = None, page: int = 1, page_size: int = 20) → Dict[str, Any]
- run_and_wait(slug: str, inputs: Dict[str, Any], run_name: str | None = None, timeout: float = 3600.0, show_progress: bool = True, poll_interval: float = 5.0) → Dict[str, Any]
- submit(slug: str, inputs: Dict[str, Any], version: int | None = None, run_name: str | None = None, environment_id: int | None = None, files: Dict[str, Any] | None = None) → ProtocolRun
- exception biolm.ProtocolNotFoundError
Bases:
ProtocolRunErrorThe requested protocol slug/version does not exist or is not accessible.
- class biolm.ProtocolRun(data: Dict[str, Any], client: ProtocolClient)
Bases:
objectA submitted protocol run returned by
ProtocolClient.submit().- cancel() → Dict[str, Any]
Cancel this run (idempotent; may error if already terminal).
- download(output_dir: str | Path = '.', file_type: str = 'csv', overwrite: bool = False) → Path
- download_files(*, output_dir: str | Path = '.', file_type: str = 'csv', overwrite: bool = False) → Path
Compatibility alias for
download().
- progress() → Dict[str, Any]
- refresh() → ProtocolRun
- results() → Dict[str, Any]
- to_dataframe(*, output_dir: str | Path = '.', overwrite: bool = False)
Download CSV zip and return a pandas DataFrame.
- wait(timeout: float = 3600.0, show_progress: bool = True, poll_interval: float = 5.0) → ProtocolRun
Block until this run reaches a terminal state.
Waiting is websocket-first: it connects to the run’s telemetry channel for live progress. If the
websocketsdependency is missing, the connection fails, or the stream closes while the run is still nonterminal, it transparently falls back to REST polling of the run detail endpoint until the run succeeds, fails, or is cancelled.- Parameters:
timeout – Total deadline in seconds shared across the websocket and REST polling phases. The deadline is not reset after a websocket failure.
show_progress – Print status changes to stdout.
poll_interval – Seconds between REST polls during fallback. Each sleep is clamped to the remaining deadline and must be greater than zero.
- Returns:
selffor chaining.- Raises:
ProtocolRunError – If the run fails or is cancelled.
TimeoutError – If the total deadline elapses before completion.
ValueError – If
poll_intervalis not greater than zero.
- exception biolm.ProtocolRunError
Bases:
ExceptionA protocol run failed, was cancelled, or the API returned an error.
- class biolm.SeqFrame(parquet_path: str | Path, ops: Tuple[Op, ...] = (), metadata: SeqFrameMetadata | None = None)
Bases:
objectSequence-centric dataframe abstraction over Parquet + DuckDB.
SeqFrames are immutable: transforming operations return new instances. Query operations are lazy until materialization (collect, write, enrich).
- property bio
- collect() → DataFrame
- property columns: List[str]
- classmethod from_csv(path: str | Path, **kwargs) → SeqFrame
- classmethod from_dataframe(df: DataFrame, *, molecule_type: str | None = None, path: str | Path | None = None) → SeqFrame
- classmethod from_fasta(path: str | Path, **kwargs) → SeqFrame
- classmethod from_jsonl(path: str | Path, **kwargs) → SeqFrame
- classmethod from_protocol(run_or_path: Any, **kwargs) → SeqFrame
- classmethod from_rows(rows: List[Dict[str, Any]], *, sequence_column: str = 'sequence', id_column: str = 'id', molecule_type: str | None = None, path: str | Path | None = None) → SeqFrame
- head(n: int = 5) → DataFrame
- property io
- property lab
- merge_columns(df: DataFrame, *, on: str = 'id') → SeqFrame
Join enrichment results back into this SeqFrame by key column.
- property models
- property protocols
- property query
- classmethod read(path: str | Path) → SeqFrame
- property schema: SeqFrameMetadata
- property shape: Tuple[int, int]
- to_dataset(dataset_id: str, *, client: Any = None, filename: str = 'sequences.parquet', tags: List[str] | None = None, description: str | None = None, attrs: Dict[str, Any] | None = None, force: bool = False) → Any
Write this SeqFrame into a local Dataset (
type: seqframe).
- write(path: str | Path) → SeqFrame
- class biolm.Volume(name: str | None = None, api_key: str | None = None)
Bases:
objectDeprecated placeholder retained for constructor and import compatibility.
- Args:
name: Legacy volume name. api_key: Legacy API token argument.
- create(name: str, **kwargs)
Reject direct local volume creation.
- delete(name: str | None = None) → bool
Reject direct local volume deletion.
- get(name: str | None = None)
Reject direct local volume lookup.
- list()
Reject direct local volume listing.
- class biolm.Workspace(account_type: str, account_id: int, environment_id: int, account: str, environment: str)
Bases:
objectImmutable account + environment pair.
account/environmentare path segments (org slug or personal label, and environment slug from the APInamefield). IDs remain authoritative.- account: str
- account_id: int
- account_type: str
- environment: str
- environment_id: int
- property path: str
- exception biolm.WorkspaceNotFoundError(message: str, status_code: int | None = None, response: Any | None = None)
Bases:
PlatformErrorNo workspace matched the requested path.
- biolm.biolm(*, entity: str, action: str, type: str | None = None, items: Any | List[Any], params: dict | None = None, api_key: str | None = None, **kwargs) → Any
Call a BioLM model in one step (sync, blocking).
Wraps
biolm.client.BioLMand returns the API result. Single-item calls return a dict; batch calls return a list.- Args:
entity: Model slug (e.g.
"esm2-8m","esmfold"). action: Model action (e.g."encode","predict","generate"). type: Item type whenitemsare plain strings (e.g."sequence"). items: One item, a list of items, or a generator of items. params: Optional action-specific parameters. api_key: Optional API token; defaults toBIOLM_TOKEN. **kwargs: Passed through tobiolm.client.BioLM.- Returns:
A single result dict or a list of result dicts (one per input item).
- biolm.encode(model_name: str, items: Any | List[Any], type: str | None = None, params: dict | None = None, **kwargs)
Quick encoding using a model.
- biolm.generate(model_name: str, items: Any | List[Any], type: str | None = None, params: dict | None = None, **kwargs)
Quick generation using a model.
- biolm.get_example(model_name: str, action: str | None = None, format: str = 'python', api_key: str | None = None, base_url: str | None = None) → str
Generate SDK usage example for a model (synchronous).
- Args:
model_name: Name of the model. action: Action name (optional, will try to detect). format: Output format (‘python’, ‘markdown’, ‘rst’, ‘json’). api_key: Optional API key. base_url: Optional base URL.
- Returns:
Formatted example string.
- biolm.list_models(api_key: str | None = None, base_url: str | None = None) → List[Dict[str, Any]]
List all available models from community-api-models endpoint (synchronous).
- Args:
api_key: Optional API key. base_url: Optional base URL.
- Returns:
List of model dictionaries.
- biolm.load_csv(file_path: str | Path | IO, sequence_key: str | None = None) → List[Dict[str, Any]]
Load data from a CSV file.
Parses a CSV file and returns a list of dictionaries suitable for use with BioLM API requests. Each row becomes a dictionary with column headers as keys. All values are kept as strings (no type inference).
- Args:
file_path: Path to CSV file (str, Path) or file-like object. sequence_key: Optional key name to validate exists in CSV; if provided, raises ValueError if column is missing.
- Returns:
List of dictionaries, one per row.
- Raises:
FileNotFoundError: If file path doesn’t exist. ValueError: If file is empty or sequence_key column is missing.
- Example:
-
default
>>> items = load_csv("data.csv", sequence_key="sequence") >>> items[0] {'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1', 'score': '0.95'}
- biolm.load_fasta(file_path: str | Path | IO) → List[Dict[str, Any]]
Load sequences from a FASTA file.
Parses a FASTA file and returns a list of dictionaries suitable for use with BioLM API requests. Each dictionary contains: - “sequence”: The sequence string - “id”: Sequence identifier from header (if available) - “metadata”: Additional metadata from header (if available)
Supports multi-line sequences (wrapped sequences).
- Args:
file_path: Path to FASTA file (str, Path) or file-like object
- Returns:
List of dictionaries, each containing sequence data
- Raises:
FileNotFoundError: If file path doesn’t exist ValueError: If file is empty or malformed
- Example:
-
default
>>> items = load_fasta("sequences.fasta") >>> items[0] {'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1', 'metadata': {}}
- biolm.load_json(file_path: str | Path | IO) → List[Dict[str, Any]]
Load data from a JSON file or JSONL (newline-delimited JSON) file.
Parses a JSON file and returns a list of dictionaries suitable for use with BioLM API requests. Supports: - Single JSON object: Returns list with one item - JSON array: Returns list of items - JSONL format (newline-delimited): Returns list of items, one per line
- Args:
file_path: Path to JSON/JSONL file (str, Path), file-like object, or “-” for stdin
- Returns:
List of dictionaries, each containing data suitable for API requests
- Raises:
FileNotFoundError: If file path doesn’t exist ValueError: If file is empty or malformed json.JSONDecodeError: If JSON is invalid
- Example:
-
default
>>> items = load_json("data.json") >>> items[0] {'sequence': 'ACDEFGHIKLMNPQRSTVWY', 'id': 'seq1'}default>>> items = load_json("data.jsonl") # JSONL format >>> len(items) 3
- biolm.load_pdb(file_path: str | Path | IO) → List[Dict[str, Any]]
Load PDB structure(s) from a PDB file.
Reads a PDB file and returns a list of dictionaries suitable for use with BioLM API requests. For single-model PDBs, returns one item. For multi-model PDBs (with MODEL/ENDMDL records), returns one item per model.
- Args:
file_path: Path to PDB file (str, Path) or file-like object
- Returns:
List of dictionaries, each containing “pdb” key with PDB content. Single-model files return [{“pdb”: “…”}]. Multi-model files return [{“pdb”: “…”}, {“pdb”: “…”}, …].
- Raises:
FileNotFoundError: If file path doesn’t exist ValueError: If file is empty
- Example:
-
default
>>> items = load_pdb("structure.pdb") >>> items[0] {'pdb': 'ATOM 1 N MET A 1 20.154 16.967 19.502...'}
- biolm.predict(model_name: str, items: Any | List[Any], type: str | None = None, params: dict | None = None, **kwargs)
Quick prediction using a model.
- biolm.run_local_protocol(protocol: dict, inputs: dict[str, Any] | None = None, *, output_dir: str | Path | None = None, verbose: bool = False, **kwargs: Any) → LocalRunResult
Run a protocol dict locally (main public API).
- biolm.run_protocol(slug: str, inputs: dict, *, run_name: str | None = None, api_key: str | None = None, base_url: str | None = None, timeout: float = 3600.0, show_progress: bool = True, poll_interval: float = 5.0) → dict
Submit a BioLM protocol run and block until results are ready.
- biolm.to_csv(data: List[Dict[str, Any]], file_path: str | Path | IO, fieldnames: List[str] | None = None) → None
Write data to a CSV file.
Converts a list of dictionaries (API response format) to CSV format.
- Args:
data: List of dictionaries to write. file_path: Output file path (str, Path), file-like object, or “-” for stdout. fieldnames: Optional list of column names; if not provided, inferred from the first item’s keys (missing keys filled with empty strings).
- Raises:
ValueError: If data is empty.
- Example:
-
default
>>> data = [{"sequence": "ACDEFGHIKLMNPQRSTVWY", "score": 0.95}] >>> to_csv(data, "output.csv")
- biolm.to_fasta(data: List[Dict[str, Any]], file_path: str | Path | IO, sequence_key: str = 'sequence') → None
Write sequences to a FASTA file.
Converts a list of dictionaries (API response format) to FASTA format. Each dictionary should contain a sequence field (default: “sequence”).
- Args:
data: List of dictionaries containing sequence data file_path: Output file path (str, Path), file-like object, or “-” for stdout sequence_key: Key to use for sequence data (default: “sequence”)
- Raises:
ValueError: If sequence_key is missing from any item KeyError: If required keys are missing
- Example:
-
default
>>> data = [{"sequence": "ACDEFGHIKLMNPQRSTVWY", "id": "seq1"}] >>> to_fasta(data, "output.fasta")
- biolm.to_json(data: List[Dict[str, Any]], file_path: str | Path | IO, indent: int = 2, jsonl: bool = False) → None
Write data to a JSON file or JSONL (newline-delimited JSON) file.
Converts a list of dictionaries (API response format) to JSON format.
- Args:
data: List of dictionaries to write. file_path: Output file path (str, Path), file-like object, or “-” for stdout. indent: Indentation level for JSON (default: 2). Use None for compact JSON. jsonl: If True, write as JSONL (one JSON object per line); if False, write as JSON array. Default: False.
- Raises:
ValueError: If data is empty.
- Example:
-
default
>>> data = [{"sequence": "ACDEFGHIKLMNPQRSTVWY", "score": 0.95}] >>> to_json(data, "output.json") >>> to_json(data, "output.jsonl", jsonl=True)
- biolm.to_pdb(data: List[Dict[str, Any]], file_path: str | Path | IO, pdb_key: str = 'pdb') → None
Write PDB structure(s) to a PDB file.
Converts a list of dictionaries (API response format) to PDB format. Each dictionary should contain a PDB content field (default: “pdb”). If multiple items are provided, they are concatenated.
- Args:
data: List of dictionaries containing PDB data file_path: Output file path (str, Path), file-like object, or “-” for stdout pdb_key: Key to use for PDB content (default: “pdb”)
- Raises:
ValueError: If data is empty or pdb_key is missing from any item
- Example:
-
default
>>> data = [{"pdb": "ATOM 1 N MET A 1..."}] >>> to_pdb(data, "output.pdb")