openprotein-python 0.4.3__py3-none-any.whl → 0.5.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. openprotein/__init__.py +40 -17
  2. openprotein/api/__init__.py +2 -7
  3. openprotein/api/align.py +68 -496
  4. openprotein/api/assaydata.py +216 -0
  5. openprotein/api/deprecated/__init__.py +0 -0
  6. openprotein/api/deprecated/poet.py +304 -0
  7. openprotein/api/design.py +7 -433
  8. openprotein/api/embedding.py +155 -999
  9. openprotein/api/fold.py +26 -319
  10. openprotein/api/job.py +91 -0
  11. openprotein/api/predict.py +25 -381
  12. openprotein/api/predictor.py +205 -0
  13. openprotein/api/svd.py +150 -0
  14. openprotein/api/train.py +42 -481
  15. openprotein/app/__init__.py +11 -0
  16. openprotein/app/models/__init__.py +20 -0
  17. openprotein/app/models/align/__init__.py +5 -0
  18. openprotein/app/models/align/base.py +20 -0
  19. openprotein/app/models/align/msa.py +140 -0
  20. openprotein/app/models/align/prompt.py +83 -0
  21. openprotein/app/models/assaydata.py +176 -0
  22. openprotein/app/models/deprecated/__init__.py +0 -0
  23. openprotein/app/models/deprecated/poet.py +183 -0
  24. openprotein/app/models/design.py +102 -0
  25. openprotein/app/models/embeddings/__init__.py +7 -0
  26. openprotein/app/models/embeddings/base.py +269 -0
  27. openprotein/app/models/embeddings/esm.py +32 -0
  28. openprotein/app/models/embeddings/future.py +98 -0
  29. openprotein/app/models/embeddings/openprotein.py +21 -0
  30. openprotein/app/models/embeddings/poet.py +393 -0
  31. openprotein/app/models/embeddings/test.py +38 -0
  32. openprotein/app/models/fold/__init__.py +6 -0
  33. openprotein/app/models/fold/alphafold2.py +50 -0
  34. openprotein/app/models/fold/base.py +81 -0
  35. openprotein/app/models/fold/esmfold.py +31 -0
  36. openprotein/app/models/fold/future.py +53 -0
  37. openprotein/app/models/futures.py +445 -0
  38. openprotein/app/models/predict.py +158 -0
  39. openprotein/app/models/predictor/__init__.py +4 -0
  40. openprotein/app/models/predictor/predict.py +78 -0
  41. openprotein/app/models/predictor/predictor.py +141 -0
  42. openprotein/app/models/svd.py +171 -0
  43. openprotein/app/models/train.py +300 -0
  44. openprotein/app/services/__init__.py +11 -0
  45. openprotein/app/services/align.py +147 -0
  46. openprotein/app/services/assaydata.py +127 -0
  47. openprotein/app/services/design.py +77 -0
  48. openprotein/app/services/embeddings.py +126 -0
  49. openprotein/app/services/fold.py +89 -0
  50. openprotein/app/services/job.py +48 -0
  51. openprotein/app/services/predict.py +139 -0
  52. openprotein/app/services/predictor.py +168 -0
  53. openprotein/app/services/svd.py +102 -0
  54. openprotein/app/services/train.py +135 -0
  55. openprotein/config.py +0 -3
  56. openprotein/errors.py +22 -5
  57. openprotein/schemas/__init__.py +59 -0
  58. openprotein/schemas/align.py +55 -0
  59. openprotein/schemas/assaydata.py +27 -0
  60. openprotein/schemas/deprecated/__init__.py +0 -0
  61. openprotein/schemas/deprecated/poet.py +70 -0
  62. openprotein/schemas/design.py +251 -0
  63. openprotein/schemas/embeddings.py +103 -0
  64. openprotein/schemas/fold.py +10 -0
  65. openprotein/schemas/job.py +110 -0
  66. openprotein/schemas/predict.py +83 -0
  67. openprotein/schemas/predictor.py +83 -0
  68. openprotein/schemas/svd.py +32 -0
  69. openprotein/schemas/train.py +34 -0
  70. {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info}/METADATA +19 -14
  71. openprotein_python-0.5.0.dev0.dist-info/RECORD +76 -0
  72. {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info}/WHEEL +1 -1
  73. openprotein/api/data.py +0 -532
  74. openprotein/api/jobs.py +0 -351
  75. openprotein/api/poet.py +0 -612
  76. openprotein/futures.py +0 -60
  77. openprotein/jobs.py +0 -186
  78. openprotein/pydantic.py +0 -20
  79. openprotein/schemas.py +0 -55
  80. openprotein_python-0.4.3.dist-info/RECORD +0 -24
  81. {openprotein_python-0.4.3.dist-info → openprotein_python-0.5.0.dev0.dist-info/licenses}/LICENSE.txt +0 -0
@@ -1,123 +1,18 @@
1
- from openprotein.base import APISession
2
- from openprotein.api.jobs import AsyncJobFuture, MappedAsyncJobFuture, job_get
3
- import openprotein.config as config
4
- from openprotein.jobs import Job, ResultsParser, JobStatus
5
- from openprotein.api.align import PromptFuture, validate_prompt
6
- from openprotein.api.poet import (
7
- PoetGenerateFuture,
8
- poet_score_post,
9
- poet_single_site_post,
10
- poet_generate_post,
11
- )
12
- from openprotein.futures import FutureBase, FutureFactory
13
-
14
- from openprotein.pydantic import BaseModel, parse_obj_as
15
- import numpy as np
16
- from typing import Optional, List, Union, Any
17
1
  import io
18
- from datetime import datetime
2
+ import random
3
+ from typing import Iterator
19
4
 
5
+ import numpy as np
6
+ from openprotein.api.align import csv_stream
7
+ from openprotein.base import APISession
8
+ from openprotein.errors import InvalidParameterError
9
+ from openprotein.schemas import AttnJob, EmbeddingsJob, Job, LogitsJob, ModelMetadata
10
+ from pydantic import TypeAdapter
20
11
 
21
12
  PATH_PREFIX = "v1/embeddings"
22
13
 
23
14
 
24
- class ModelDescription(BaseModel):
25
- citation_title: Optional[str] = None
26
- doi: Optional[str] = None
27
- summary: str = "Protein language model for embeddings"
28
-
29
-
30
- class TokenInfo(BaseModel):
31
- id: int
32
- token: str
33
- primary: bool
34
- description: str
35
-
36
-
37
- class ModelMetadata(BaseModel):
38
- model_id: str
39
- description: ModelDescription
40
- max_sequence_length: Optional[int] = None
41
- dimension: int
42
- output_types: List[str]
43
- input_tokens: List[str]
44
- output_tokens: Optional[List[str]] = None
45
- token_descriptions: List[List[TokenInfo]]
46
-
47
-
48
- class EmbeddedSequence(BaseModel):
49
- class Config:
50
- arbitrary_types_allowed = True
51
-
52
- sequence: bytes
53
- embedding: np.ndarray
54
-
55
- def __iter__(self):
56
- yield self.sequence
57
- yield self.embedding
58
-
59
- def __len__(self):
60
- return 2
61
-
62
- def __getitem__(self, i):
63
- if i == 0:
64
- return self.sequence
65
- elif i == 1:
66
- return self.embedding
67
-
68
-
69
- class SVDMetadata(BaseModel):
70
- id: str
71
- status: JobStatus
72
- created_date: Optional[datetime] = None
73
- model_id: str
74
- n_components: int
75
- reduction: Optional[str] = None
76
- sequence_length: Optional[int] = None
77
-
78
- def is_done(self):
79
- return self.status.done()
80
-
81
-
82
- # split these out by module for another layer of control
83
- class EmbBase:
84
- # overridden by subclasses
85
- # get correct emb model
86
- model_id = None
87
-
88
- @classmethod
89
- def get_model(cls):
90
- if isinstance(cls.model_id, str):
91
- return [cls.model_id]
92
- return cls.model_id
93
-
94
-
95
- class EmbFactory:
96
- """Factory class for creating Future instances based on job_type."""
97
-
98
- @staticmethod
99
- def create_model(session, model_id, default=None):
100
- """
101
- Create and return an instance of the appropriate Future class based on the job type.
102
-
103
- Returns:
104
- - An instance of the appropriate Future class.
105
- """
106
- # Dynamically discover all subclasses of FutureBase
107
- future_classes = EmbBase.__subclasses__()
108
-
109
- # Find the Future class that matches the job type
110
- for future_class in future_classes:
111
- if model_id in future_class.get_model():
112
- return future_class(session=session, model_id=model_id)
113
- # default to ProtembedModel
114
- try:
115
- return default(session=session, model_id=model_id)
116
- except Exception: # type: ignore
117
- raise ValueError(f"Unsupported model_id type: {model_id}")
118
-
119
-
120
- def embedding_models_list_get(session: APISession) -> List[str]:
15
+ def list_models(session: APISession) -> list[str]:
121
16
  """
122
17
  List available embeddings models.
123
18
 
@@ -125,7 +20,7 @@ def embedding_models_list_get(session: APISession) -> List[str]:
125
20
  session (APISession): API session
126
21
 
127
22
  Returns:
128
- List[str]: list of model names.
23
+ list[str]: list of model names.
129
24
  """
130
25
 
131
26
  endpoint = PATH_PREFIX + "/models"
@@ -134,35 +29,14 @@ def embedding_models_list_get(session: APISession) -> List[str]:
134
29
  return result
135
30
 
136
31
 
137
- def embedding_model_get(session: APISession, model_id: str) -> ModelMetadata:
32
+ def get_model(session: APISession, model_id: str) -> ModelMetadata:
138
33
  endpoint = PATH_PREFIX + f"/models/{model_id}"
139
34
  response = session.get(endpoint)
140
35
  result = response.json()
141
36
  return ModelMetadata(**result)
142
37
 
143
38
 
144
- def embedding_get(session: APISession, job_id: str) -> FutureBase:
145
- """
146
- Get Job associated with the given request ID.
147
-
148
- Parameters
149
- ----------
150
- session : APISession
151
- Session object for API communication.
152
- job_id : str
153
- job ID to fetch
154
-
155
- Returns
156
- -------
157
- sequences : List[bytes]
158
- """
159
-
160
- # endpoint = PATH_PREFIX + f"/{job_id}"
161
- # response = session.get(endpoint)
162
- return FutureFactory.create_future(session=session, job_id=job_id)
163
-
164
-
165
- def embedding_get_sequences(session: APISession, job_id: str) -> List[bytes]:
39
+ def get_request_sequences(session: APISession, job_id: str) -> list[bytes]:
166
40
  """
167
41
  Get results associated with the given request ID.
168
42
 
@@ -179,11 +53,11 @@ def embedding_get_sequences(session: APISession, job_id: str) -> List[bytes]:
179
53
  """
180
54
  endpoint = PATH_PREFIX + f"/{job_id}/sequences"
181
55
  response = session.get(endpoint)
182
- return parse_obj_as(List[bytes], response.json())
56
+ return TypeAdapter(list[bytes]).validate_python(response.json())
183
57
 
184
58
 
185
- def embedding_get_sequence_result(
186
- session: APISession, job_id: str, sequence: bytes
59
+ def request_get_sequence_result(
60
+ session: APISession, job_id: str, sequence: str | bytes
187
61
  ) -> bytes:
188
62
  """
189
63
  Get encoded result for a sequence from the request ID.
@@ -208,7 +82,7 @@ def embedding_get_sequence_result(
208
82
  return response.content
209
83
 
210
84
 
211
- def decode_embedding(data: bytes) -> np.ndarray:
85
+ def result_decode(data: bytes) -> np.ndarray:
212
86
  """
213
87
  Decode embedding.
214
88
 
@@ -222,66 +96,55 @@ def decode_embedding(data: bytes) -> np.ndarray:
222
96
  return np.load(s, allow_pickle=False)
223
97
 
224
98
 
225
- class EmbeddingResultFuture(MappedAsyncJobFuture, FutureBase):
226
- """Future Job for manipulating results"""
227
-
228
- job_type = [
229
- "/embeddings/embed",
230
- "/embeddings/svd",
231
- "/embeddings/attn",
232
- "/embeddings/logits",
233
- "/embeddings/embed_reduced",
234
- "/svd/fit",
235
- "/svd/embed",
236
- ]
237
-
238
- def __init__(
239
- self,
240
- session: APISession,
241
- job: Job,
242
- sequences=None,
243
- max_workers=config.MAX_CONCURRENT_WORKERS,
244
- ):
245
- super().__init__(session, job, max_workers)
246
- self._sequences = sequences
247
-
248
- def get(self, verbose=False) -> List:
249
- return super().get(verbose=verbose)
99
+ def request_get_score_result(session: APISession, job_id: str) -> Iterator[list[str]]:
100
+ """
101
+ Get encoded result for a sequence from the request ID.
250
102
 
251
- @property
252
- def sequences(self):
253
- if self._sequences is None:
254
- self._sequences = embedding_get_sequences(self.session, self.job.job_id)
255
- return self._sequences
103
+ Parameters
104
+ ----------
105
+ session : APISession
106
+ Session object for API communication.
107
+ job_id : str
108
+ job ID to retrieve results from
256
109
 
257
- @property
258
- def id(self):
259
- return self.job.job_id
110
+ Returns
111
+ -------
112
+ csv.reader
113
+ """
114
+ endpoint = PATH_PREFIX + f"/{job_id}/scores"
115
+ response = session.get(endpoint, stream=True)
116
+ return csv_stream(response)
260
117
 
261
- def keys(self):
262
- return self.sequences
263
118
 
264
- def get_item(self, sequence: bytes) -> np.ndarray:
265
- """
266
- Get embedding results for specified sequence.
119
+ def request_get_generate_result(
120
+ session: APISession, job_id: str
121
+ ) -> Iterator[list[str]]:
122
+ """
123
+ Get encoded result for a sequence from the request ID.
267
124
 
268
- Args:
269
- sequence (bytes): sequence to fetch results for
125
+ Parameters
126
+ ----------
127
+ session : APISession
128
+ Session object for API communication.
129
+ job_id : str
130
+ job ID to retrieve results from
270
131
 
271
- Returns:
272
- np.ndarray: embeddings
273
- """
274
- data = embedding_get_sequence_result(self.session, self.job.job_id, sequence)
275
- return decode_embedding(data)
132
+ Returns
133
+ -------
134
+ csv.reader
135
+ """
136
+ endpoint = PATH_PREFIX + f"/{job_id}/generate"
137
+ response = session.get(endpoint, stream=True)
138
+ return csv_stream(response)
276
139
 
277
140
 
278
- def embedding_model_post(
141
+ def request_post(
279
142
  session: APISession,
280
143
  model_id: str,
281
- sequences: List[bytes],
282
- reduction: Optional[str] = "MEAN",
283
- prompt_id: Optional[str] = None,
284
- ):
144
+ sequences: list[bytes] | list[str],
145
+ reduction: str | None = "MEAN",
146
+ prompt_id: str | None = None,
147
+ ) -> EmbeddingsJob:
285
148
  """
286
149
  POST a request for embeddings from the given model ID. Returns a Job object referring to this request
287
150
  that can be used to retrieve results later.
@@ -294,7 +157,7 @@ def embedding_model_post(
294
157
  model ID to request results from
295
158
  sequences : List[bytes]
296
159
  sequences to request results for
297
- reduction : Optional[str]
160
+ reduction : str | None
298
161
  reduction to apply to the embeddings. options are None, "MEAN", or "SUM". defaul: "MEAN"
299
162
  kwargs:
300
163
  accepts prompt_id for Poet Jobs
@@ -306,24 +169,23 @@ def embedding_model_post(
306
169
  endpoint = PATH_PREFIX + f"/models/{model_id}/embed"
307
170
 
308
171
  sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
309
- body = {
172
+ body: dict = {
310
173
  "sequences": sequences_unicode,
311
174
  }
312
- if "prompt_id":
175
+ if prompt_id is not None:
313
176
  body["prompt_id"] = prompt_id
314
- body["reduction"] = reduction
177
+ if reduction is not None:
178
+ body["reduction"] = reduction
315
179
  response = session.post(endpoint, json=body)
316
- return FutureFactory.create_future(
317
- session=session, response=response, sequences=sequences
318
- )
180
+ return EmbeddingsJob.model_validate(response.json())
319
181
 
320
182
 
321
- def embedding_model_logits_post(
183
+ def request_logits_post(
322
184
  session: APISession,
323
185
  model_id: str,
324
- sequences: List[bytes],
325
- prompt_id: Optional[str] = None,
326
- ) -> Job:
186
+ sequences: list[bytes] | list[str],
187
+ prompt_id: str | None = None,
188
+ ) -> LogitsJob:
327
189
  """
328
190
  POST a request for logits from the given model ID. Returns a Job object referring to this request
329
191
  that can be used to retrieve results later.
@@ -344,23 +206,21 @@ def embedding_model_logits_post(
344
206
  endpoint = PATH_PREFIX + f"/models/{model_id}/logits"
345
207
 
346
208
  sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
347
- body = {
209
+ body: dict = {
348
210
  "sequences": sequences_unicode,
349
211
  }
350
- if "prompt_id":
212
+ if prompt_id is not None:
351
213
  body["prompt_id"] = prompt_id
352
214
  response = session.post(endpoint, json=body)
353
- return FutureFactory.create_future(
354
- session=session, response=response, sequences=sequences
355
- )
215
+ return LogitsJob.model_validate(response.json())
356
216
 
357
217
 
358
- def embedding_model_attn_post(
218
+ def request_attn_post(
359
219
  session: APISession,
360
220
  model_id: str,
361
- sequences: List[bytes],
362
- prompt_id: Optional[str] = None,
363
- ) -> Job:
221
+ sequences: list[bytes] | list[str],
222
+ prompt_id: str | None = None,
223
+ ) -> AttnJob:
364
224
  """
365
225
  POST a request for attention embeddings from the given model ID. \
366
226
  Returns a Job object referring to this request \
@@ -382,843 +242,139 @@ def embedding_model_attn_post(
382
242
  endpoint = PATH_PREFIX + f"/models/{model_id}/attn"
383
243
 
384
244
  sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
385
- body = {
245
+ body: dict = {
386
246
  "sequences": sequences_unicode,
387
247
  }
388
- if "prompt_id":
248
+ if prompt_id is not None:
389
249
  body["prompt_id"] = prompt_id
390
250
  response = session.post(endpoint, json=body)
391
- return FutureFactory.create_future(
392
- session=session, response=response, sequences=sequences
393
- )
394
-
395
-
396
- def svd_list_get(session: APISession) -> List[SVDMetadata]:
397
- """Get SVD job metadata for all SVDs. Including SVD dimension and sequence lengths."""
398
- endpoint = PATH_PREFIX + "/svd"
399
- response = session.get(endpoint)
400
- return parse_obj_as(List[SVDMetadata], response.json())
251
+ return AttnJob.model_validate(response.json())
401
252
 
402
253
 
403
- def svd_get(session: APISession, svd_id: str) -> SVDMetadata:
404
- """Get SVD job metadata. Including SVD dimension and sequence lengths."""
405
- endpoint = PATH_PREFIX + f"/svd/{svd_id}"
406
- response = session.get(endpoint)
407
- return SVDMetadata(**response.json())
408
-
409
-
410
- def svd_delete(session: APISession, svd_id: str):
254
+ def request_score_post(
255
+ session: APISession,
256
+ model_id: str,
257
+ sequences: list[bytes] | list[str],
258
+ prompt_id: str | None = None,
259
+ ) -> Job:
411
260
  """
412
- Delete and SVD model.
261
+ POST a request for sequence scoring for the given model ID. \
262
+ Returns a Job object referring to this request \
263
+ that can be used to retrieve results later.
413
264
 
414
265
  Parameters
415
266
  ----------
416
267
  session : APISession
417
268
  Session object for API communication.
418
- svd_id : str
419
- SVD model to delete
269
+ model_id : str
270
+ model ID to request results from
271
+ sequences : List[bytes]
272
+ sequences to request results for
420
273
 
421
274
  Returns
422
275
  -------
423
- bool
276
+ job : Job
424
277
  """
278
+ endpoint = PATH_PREFIX + f"/models/{model_id}/score"
425
279
 
426
- endpoint = PATH_PREFIX + f"/svd/{svd_id}"
427
- session.delete(endpoint)
428
- return True
280
+ sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
281
+ body: dict = {
282
+ "sequences": sequences_unicode,
283
+ }
284
+ if prompt_id is not None:
285
+ body["prompt_id"] = prompt_id
286
+ response = session.post(endpoint, json=body)
287
+ return Job.model_validate(response.json())
429
288
 
430
289
 
431
- def svd_fit_post(
290
+ def request_score_single_site_post(
432
291
  session: APISession,
433
292
  model_id: str,
434
- sequences: List[bytes],
435
- n_components: int = 1024,
436
- reduction: Optional[str] = None,
437
- prompt_id: Optional[str] = None,
438
- ):
293
+ base_sequence: bytes,
294
+ prompt_id: str | None = None,
295
+ ) -> Job:
439
296
  """
440
- Create SVD fit job.
297
+ POST a request for single site mutation scoring for the given model ID. \
298
+ Returns a Job object referring to this request \
299
+ that can be used to retrieve results later.
441
300
 
442
301
  Parameters
443
302
  ----------
444
303
  session : APISession
445
304
  Session object for API communication.
446
305
  model_id : str
447
- model to use
306
+ model ID to request results from
448
307
  sequences : List[bytes]
449
- sequences to SVD
450
- n_components : int
451
- number of SVD components to fit. default = 1024
452
- reduction : Optional[str]
453
- embedding reduction to use for fitting the SVD. default = None
308
+ sequences to request results for
454
309
 
455
310
  Returns
456
311
  -------
457
- SVDJob
312
+ job : Job
458
313
  """
314
+ endpoint = PATH_PREFIX + f"/models/{model_id}/score_single_site"
459
315
 
460
- endpoint = PATH_PREFIX + "/svd"
461
-
462
- sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
463
- body = {
464
- "model_id": model_id,
465
- "sequences": sequences_unicode,
466
- "n_components": n_components,
316
+ body: dict = {
317
+ "base_sequence": base_sequence.decode(),
467
318
  }
468
- if reduction is not None:
469
- body["reduction"] = reduction
470
319
  if prompt_id is not None:
471
320
  body["prompt_id"] = prompt_id
472
-
473
321
  response = session.post(endpoint, json=body)
474
- # return job for metadata
475
- return ResultsParser.parse_obj(response)
322
+ return Job.model_validate(response.json())
476
323
 
477
324
 
478
- def svd_embed_post(session: APISession, svd_id: str, sequences: List[bytes]) -> Job:
325
+ def request_generate_post(
326
+ session: APISession,
327
+ model_id: str,
328
+ num_samples: int = 100,
329
+ temperature: float = 1.0,
330
+ topk: float | None = None,
331
+ topp: float | None = None,
332
+ max_length: int = 1000,
333
+ random_seed: int | None = None,
334
+ prompt_id: str | None = None,
335
+ ) -> Job:
479
336
  """
480
- POST a request for embeddings from the given SVD model.
337
+ POST a request for sequence generation for the given model ID. \
338
+ Returns a Job object referring to this request \
339
+ that can be used to retrieve results later.
481
340
 
482
341
  Parameters
483
342
  ----------
484
343
  session : APISession
485
344
  Session object for API communication.
486
- svd_id : str
487
- SVD model to use
488
- sequences : List[bytes]
489
- sequences to SVD
345
+ model_id : str
346
+ model ID to request results from
490
347
 
491
348
  Returns
492
349
  -------
493
- Job
494
- """
495
- endpoint = PATH_PREFIX + f"/svd/{svd_id}/embed"
496
-
497
- sequences_unicode = [(s if isinstance(s, str) else s.decode()) for s in sequences]
498
- body = {
499
- "sequences": sequences_unicode,
500
- }
501
- response = session.post(endpoint, json=body)
502
-
503
- return FutureFactory.create_future(
504
- session=session, response=response, sequences=sequences
505
- )
506
-
507
-
508
- class ProtembedModel(EmbBase):
509
- """
510
- Class providing inference endpoints for protein embedding models served by OpenProtein.
511
- """
512
-
513
- model_id = "protembed"
514
-
515
- def __init__(self, session, model_id, metadata=None):
516
- self.session = session
517
- self.id = model_id
518
- self._metadata = metadata
519
- self.__doc__ = self.__fmt_doc()
520
-
521
- def __fmt_doc(self):
522
- summary = str(self.metadata.description.summary)
523
- return f"""\t{summary}
524
- \t max_sequence_length = {self.metadata.max_sequence_length}
525
- \t supported outputs = {self.metadata.output_types}
526
- \t supported tokens = {self.metadata.input_tokens}
527
- """
528
-
529
- def __str__(self) -> str:
530
- return self.id
531
-
532
- def __repr__(self) -> str:
533
- return self.id
534
-
535
- @property
536
- def metadata(self):
537
- if self._metadata is None:
538
- self._metadata = self.get_metadata()
539
- return self._metadata
540
-
541
- def get_metadata(self) -> ModelMetadata:
542
- """
543
- Get model metadata for this model.
544
-
545
- Returns
546
- -------
547
- ModelMetadata
548
- """
549
- if self._metadata is not None:
550
- return self._metadata
551
- self._metadata = embedding_model_get(self.session, self.id)
552
- return self._metadata
553
-
554
- def embed(
555
- self, sequences: List[bytes], reduction: Optional[str] = "MEAN"
556
- ) -> EmbeddingResultFuture:
557
- """
558
- Embed sequences using this model.
559
-
560
- Parameters
561
- ----------
562
- sequences : List[bytes]
563
- sequences to SVD
564
- reduction: str
565
- embeddings reduction to use (e.g. mean)
566
-
567
- Returns
568
- -------
569
- EmbeddingResultFuture
570
- """
571
- return embedding_model_post(
572
- self.session, model_id=self.id, sequences=sequences, reduction=reduction
573
- )
574
-
575
- def logits(self, sequences: List[bytes]) -> EmbeddingResultFuture:
576
- """
577
- logit embeddings for sequences using this model.
578
-
579
- Parameters
580
- ----------
581
- sequences : List[bytes]
582
- sequences to SVD
583
-
584
- Returns
585
- -------
586
- EmbeddingResultFuture
587
- """
588
- return embedding_model_logits_post(self.session, self.id, sequences)
589
-
590
- def attn(self, sequences: List[bytes]) -> EmbeddingResultFuture:
591
- """
592
- Attention embeddings for sequences using this model.
593
-
594
- Parameters
595
- ----------
596
- sequences : List[bytes]
597
- sequences to SVD
598
-
599
- Returns
600
- -------
601
- EmbeddingResultFuture
602
- """
603
- return embedding_model_attn_post(self.session, self.id, sequences)
604
-
605
- def fit_svd(
606
- self,
607
- sequences: List[bytes],
608
- n_components: int = 1024,
609
- reduction: Optional[str] = None,
610
- ) -> Any:
611
- """
612
- Fit an SVD on the embedding results of this model.
613
-
614
- This function will create an SVDModel based on the embeddings from this model \
615
- as well as the hyperparameters specified in the args.
616
-
617
- Parameters
618
- ----------
619
- sequences : List[bytes]
620
- sequences to SVD
621
- n_components: int
622
- number of components in SVD. Will determine output shapes
623
- reduction: str
624
- embeddings reduction to use (e.g. mean)
625
-
626
- Returns
627
- -------
628
- SVDModel
629
- """
630
- model_id = self.id
631
- job = svd_fit_post(
632
- self.session,
633
- model_id,
634
- sequences,
635
- n_components=n_components,
636
- reduction=reduction,
637
- )
638
- if isinstance(job, Job):
639
- job_id = job.job_id
640
- else:
641
- job_id = job.job.job_id
642
- metadata = svd_get(self.session, job_id)
643
- return SVDModel(self.session, metadata)
644
-
645
-
646
- class SVDModel(AsyncJobFuture, FutureBase):
647
- """
648
- Class providing embedding endpoint for SVD models. \
649
- Also allows retrieving embeddings of sequences used to fit the SVD with `get`.
650
- """
651
-
652
- # actually a future, not a model!
653
- job_type = "/svd"
654
-
655
- def __init__(self, session: APISession, metadata: SVDMetadata):
656
- self.session = session
657
- self._metadata = metadata
658
- self._job = None
659
-
660
- def __str__(self) -> str:
661
- return str(self.metadata)
662
-
663
- def __repr__(self) -> str:
664
- return repr(self.metadata)
665
-
666
- @property
667
- def metadata(self):
668
- self._refresh_metadata()
669
- return self._metadata
670
-
671
- def _refresh_metadata(self):
672
- if not self._metadata.is_done():
673
- self._metadata = svd_get(self.session, self.id)
674
-
675
- @property
676
- def id(self):
677
- return self._metadata.id
678
-
679
- @property
680
- def n_components(self):
681
- return self._metadata.n_components
682
-
683
- @property
684
- def sequence_length(self):
685
- return self._metadata.sequence_length
686
-
687
- @property
688
- def reduction(self):
689
- return self._metadata.reduction
690
-
691
- def get_model(self) -> ProtembedModel:
692
- """Fetch embeddings model"""
693
- model = ProtembedModel(self.session, self._metadata.model_id)
694
- return model
695
-
696
- @property
697
- def model(self) -> ProtembedModel:
698
- return self.get_model()
699
-
700
- def delete(self) -> bool:
701
- """
702
- Delete this SVD model.
703
- """
704
- return svd_delete(self.session, self.id)
705
-
706
- def get_job(self) -> Job:
707
- """Get job associated with this SVD model"""
708
- return job_get(self.session, self.id)
709
-
710
- def get(self, verbose: bool = False):
711
- # overload for AsyncJobFuture
712
- return self
713
-
714
- @property
715
- def job(self) -> Job:
716
- if self._job is None:
717
- self._job = self.get_job()
718
- return self._job
719
-
720
- @job.setter
721
- def job(self, j):
722
- self._job = j
723
-
724
- def get_inputs(self) -> List[bytes]:
725
- """
726
- Get sequences used for embeddings job.
727
-
728
- Returns
729
- -------
730
- List[bytes]: list of sequences
731
- """
732
- return embedding_get_sequences(self.session, job_id=self.id)
733
-
734
- def get_embeddings(self) -> EmbeddingResultFuture:
735
- """
736
- Get SVD embedding results for this model.
737
-
738
- Returns
739
- -------
740
- EmbeddingResultFuture: class for futher job manipulation
741
- """
742
- return EmbeddingResultFuture(self.session, self.get_job())
743
-
744
- def embed(self, sequences: List[bytes]) -> EmbeddingResultFuture:
745
- """
746
- Use this SVD model to reduce embeddings results.
747
-
748
- Parameters
749
- ----------
750
- sequences : List[bytes]
751
- List of protein sequences.
752
-
753
- Returns
754
- -------
755
- EmbeddingResultFuture
756
- Class for further job manipulation.
757
- """
758
- return svd_embed_post(self.session, self.id, sequences)
759
- # return EmbeddingResultFuture(self.session, job, sequences=sequences)
760
-
761
-
762
- class OpenProteinModel(ProtembedModel):
763
- """
764
- Class providing inference endpoints for proprietary protein embedding models served by OpenProtein.
765
-
766
- Examples
767
- --------
768
- View specific model details (inc supported tokens) with the `?` operator.
769
-
770
- .. code-block:: python
771
-
772
- import openprotein
773
- session = openprotein.connect(username="user", password="password")
774
- session.embedding.prot_seq?
775
- """
776
-
777
-
778
- class PoETModel(OpenProteinModel, EmbBase):
779
- """
780
- Class for OpenProtein's foundation model PoET - NB. PoET functions are dependent on a prompt supplied via the align endpoints.
781
-
782
- Examples
783
- --------
784
- View specific model details (inc supported tokens) with the `?` operator.
785
-
786
- .. code-block:: python
787
-
788
- import openprotein
789
- session = openprotein.connect(username="user", password="password")
790
- session.embedding.poet?
791
-
792
-
793
- """
794
-
795
- model_id = "poet"
796
-
797
- # Add model to explicitly require prompt_id
798
- def __init__(self, session, model_id, metadata=None):
799
- self.session = session
800
- self.id = model_id
801
- self._metadata = metadata
802
- # could add prompt here?
803
-
804
- def embed(
805
- self,
806
- prompt: Union[str, PromptFuture],
807
- sequences: List[bytes],
808
- reduction: Optional[str] = "MEAN",
809
- ) -> EmbeddingResultFuture:
810
- """
811
- Embed sequences using this model.
812
-
813
- Parameters
814
- ----------
815
- prompt: Union[str, PromptFuture]
816
- prompt from an align workflow to condition Poet model
817
- sequence : bytes
818
- Sequence to embed.
819
- reduction: str
820
- embeddings reduction to use (e.g. mean)
821
- Returns
822
- -------
823
- EmbeddingResultFuture
824
- """
825
- prompt_id = validate_prompt(prompt)
826
- # return super().embed(sequences=sequences, reduction=reduction, prompt_id=prompt_id)
827
- return embedding_model_post(
828
- self.session,
829
- model_id=self.id,
830
- sequences=sequences,
831
- prompt_id=prompt_id,
832
- reduction=reduction,
833
- )
834
-
835
- def logits(
836
- self,
837
- prompt: Union[str, PromptFuture],
838
- sequences: List[bytes],
839
- ) -> EmbeddingResultFuture:
840
- """
841
- logit embeddings for sequences using this model.
842
-
843
- Parameters
844
- ----------
845
- prompt: Union[str, PromptFuture]
846
- prompt from an align workflow to condition Poet model
847
- sequence : bytes
848
- Sequence to analyse.
849
-
850
- Returns
851
- -------
852
- EmbeddingResultFuture
853
- """
854
- prompt_id = validate_prompt(prompt)
855
- # return super().logits(sequences=sequences, prompt_id=prompt_id)
856
- return embedding_model_logits_post(
857
- self.session, self.id, sequences=sequences, prompt_id=prompt_id
858
- )
859
-
860
- def attn():
861
- """Not Available for Poet."""
862
- raise ValueError("Attn not yet supported for poet")
863
-
864
- def score(self, prompt: Union[str, PromptFuture], sequences: List[bytes]):
865
- """
866
- Score query sequences using the specified prompt.
867
-
868
- Parameters
869
- ----------
870
- prompt: Union[str, PromptFuture]
871
- prompt from an align workflow to condition Poet model
872
- sequence : bytes
873
- Sequence to analyse.
874
- Returns
875
- -------
876
- results
877
- The scores of the query sequences.
878
- """
879
- prompt_id = validate_prompt(prompt)
880
- return poet_score_post(self.session, prompt_id, sequences)
881
-
882
- def single_site(self, prompt: Union[str, PromptFuture], sequence: bytes):
883
- """
884
- Score all single substitutions of the query sequence using the specified prompt.
885
-
886
- Parameters
887
- ----------
888
- prompt: Union[str, PromptFuture]
889
- prompt from an align workflow to condition Poet model
890
- sequence : bytes
891
- Sequence to analyse.
892
- Returns
893
- -------
894
- results
895
- The scores of the mutated sequence.
896
- """
897
- prompt_id = validate_prompt(prompt)
898
- return poet_single_site_post(self.session, sequence, prompt_id=prompt_id)
899
-
900
- def generate(
901
- self,
902
- prompt: Union[str, PromptFuture],
903
- num_samples=100,
904
- temperature=1.0,
905
- topk=None,
906
- topp=None,
907
- max_length=1000,
908
- seed=None,
909
- ) -> PoetGenerateFuture:
910
- """
911
- Generate protein sequences conditioned on a prompt.
912
-
913
- Parameters
914
- ----------
915
- prompt: Union[str, PromptFuture]
916
- prompt from an align workflow to condition Poet model
917
- num_samples : int, optional
918
- The number of samples to generate, by default 100.
919
- temperature : float, optional
920
- The temperature for sampling. Higher values produce more random outputs, by default 1.0.
921
- topk : int, optional
922
- The number of top-k residues to consider during sampling, by default None.
923
- topp : float, optional
924
- The cumulative probability threshold for top-p sampling, by default None.
925
- max_length : int, optional
926
- The maximum length of generated proteins, by default 1000.
927
- seed : int, optional
928
- Seed for random number generation, by default a random number.
929
-
930
- Raises
931
- ------
932
- APIError
933
- If there is an issue with the API request.
934
-
935
- Returns
936
- -------
937
- Job
938
- An object representing the status and information about the generation job.
939
- """
940
- prompt_id = validate_prompt(prompt)
941
- return poet_generate_post(
942
- self.session,
943
- prompt_id,
944
- num_samples=num_samples,
945
- temperature=temperature,
946
- topk=topk,
947
- topp=topp,
948
- max_length=max_length,
949
- random_seed=seed,
950
- )
951
-
952
- def fit_svd(
953
- self,
954
- prompt: Union[str, PromptFuture],
955
- sequences: List[bytes],
956
- n_components: int = 1024,
957
- reduction: Optional[str] = None,
958
- ) -> SVDModel: # type: ignore
959
- """
960
- Fit an SVD on the embedding results of this model.
961
-
962
- This function will create an SVDModel based on the embeddings from this model \
963
- as well as the hyperparameters specified in the args.
964
-
965
- Parameters
966
- ----------
967
- prompt: Union[str, PromptFuture]
968
- prompt from an align workflow to condition Poet model
969
- sequences : List[bytes]
970
- sequences to SVD
971
- n_components: int
972
- number of components in SVD. Will determine output shapes
973
- reduction: str
974
- embeddings reduction to use (e.g. mean)
975
-
976
-
977
- Returns
978
- -------
979
- SVDModel
980
- """
981
- prompt = validate_prompt(prompt)
982
-
983
- job = svd_fit_post(
984
- self.session,
985
- model_id=self.id,
986
- sequences=sequences,
987
- n_components=n_components,
988
- reduction=reduction,
989
- prompt_id=prompt,
990
- )
991
- metadata = svd_get(self.session, job.job_id)
992
- return SVDModel(self.session, metadata)
993
-
994
-
995
- class ESMModel(ProtembedModel):
996
- """
997
- Class providing inference endpoints for Facebook's ESM protein language Models.
998
-
999
- Examples
1000
- --------
1001
- View specific model details (inc supported tokens) with the `?` operator.
1002
-
1003
- .. code-block:: python
1004
-
1005
- import openprotein
1006
- session = openprotein.connect(username="user", password="password")
1007
- session.embedding.esm2_t12_35M_UR50D?"""
1008
-
1009
-
1010
- class EmbeddingAPI:
1011
- """
1012
- This class defines a high level interface for accessing the embeddings API.
1013
-
1014
- You can access all our models either via :meth:`get_model` or directly through the session's embedding attribute using the model's ID and the desired method. For example, to use the attention method on the protein sequence model, you would use ``session.embedding.prot_seq.attn()``.
1015
-
1016
- Examples
1017
- --------
1018
- Accessing a model's method:
1019
-
1020
- .. code-block:: python
1021
-
1022
- # To call the attention method on the protein sequence model:
1023
- import openprotein
1024
- session = openprotein.connect(username="user", password="password")
1025
- session.embedding.prot_seq.attn()
1026
-
1027
- Using the `get_model` method:
1028
-
1029
- .. code-block:: python
1030
-
1031
- # Get a model instance by name:
1032
- import openprotein
1033
- session = openprotein.connect(username="user", password="password")
1034
- # list available models:
1035
- print(session.embedding.list_models() )
1036
- # init model by name
1037
- model = session.embedding.get_model('prot-seq')
350
+ job : Job
1038
351
  """
352
+ endpoint = PATH_PREFIX + f"/models/{model_id}/generate"
1039
353
 
1040
- # added for static typing, eg pylance, for autocomplete
1041
- # at init these are all overwritten.
1042
- prot_seq: OpenProteinModel
1043
- rotaprot_large_uniref50w: OpenProteinModel
1044
- rotaprot_large_uniref90_ft: OpenProteinModel
1045
- poet: PoETModel
1046
-
1047
- esm1b_t33_650M_UR50S: ESMModel
1048
- esm1v_t33_650M_UR90S_1: ESMModel
1049
- esm1v_t33_650M_UR90S_2: ESMModel
1050
- esm1v_t33_650M_UR90S_3: ESMModel
1051
- esm1v_t33_650M_UR90S_4: ESMModel
1052
- esm1v_t33_650M_UR90S_5: ESMModel
1053
- esm2_t12_35M_UR50D: ESMModel
1054
- esm2_t30_150M_UR50D: ESMModel
1055
- esm2_t33_650M_UR50D: ESMModel
1056
- esm2_t36_3B_UR50D: ESMModel
1057
- esm2_t6_8M_UR50D: ESMModel
1058
-
1059
- def __init__(self, session: APISession):
1060
- self.session = session
1061
- # dynamically add models from api list
1062
- self._load_models()
1063
-
1064
- def _load_models(self):
1065
- # Dynamically add model instances as attributes - precludes any drift
1066
- models = self.list_models()
1067
- for model in models:
1068
- model_name = model.id.replace("-", "_") # hyphens out
1069
- setattr(self, model_name, model)
1070
-
1071
- def list_models(self) -> List[ProtembedModel]:
1072
- """list models available for creating embeddings of your sequences"""
1073
- models = []
1074
- for model_id in embedding_models_list_get(self.session):
1075
- models.append(
1076
- EmbFactory.create_model(
1077
- session=self.session, model_id=model_id, default=ProtembedModel
1078
- )
1079
- )
1080
- return models
1081
-
1082
- def get_model(self, name: str):
1083
- """
1084
- Get model by model_id.
1085
-
1086
- ProtembedModel allows all the usual job manipulation: \
1087
- e.g. making POST and GET requests for this model specifically.
1088
-
1089
-
1090
- Parameters
1091
- ----------
1092
- model_id : str
1093
- the model identifier
1094
-
1095
- Returns
1096
- -------
1097
- ProtembedModel
1098
- The model
1099
-
1100
- Raises
1101
- ------
1102
- HTTPError
1103
- If the GET request does not succeed.
1104
- """
1105
- model_name = name.replace("-", "_")
1106
- return getattr(self, model_name)
1107
-
1108
- def __get_results(self, job) -> EmbeddingResultFuture:
1109
- """
1110
- Retrieves the results of an embedding job.
1111
-
1112
- Parameters
1113
- ----------
1114
- job : Job
1115
- The embedding job whose results are to be retrieved.
1116
-
1117
- Returns
1118
- -------
1119
- EmbeddingResultFuture
1120
- An instance of EmbeddingResultFuture
1121
- """
1122
- return FutureFactory.create_future(job=job, session=self.session)
1123
-
1124
- def __fit_svd(
1125
- self,
1126
- model_id: str,
1127
- sequences: List[bytes],
1128
- n_components: int = 1024,
1129
- reduction: Optional[str] = None,
1130
- **kwargs,
1131
- ) -> SVDModel:
1132
- """
1133
- Fit an SVD on the sequences with the specified model_id and hyperparameters (n_components).
1134
-
1135
- Parameters
1136
- ----------
1137
- model_id : str
1138
- The ID of the model to fit the SVD on.
1139
- sequences : List[bytes]
1140
- The list of sequences to use for the SVD fitting.
1141
- n_components : int, optional
1142
- The number of components for the SVD, by default 1024.
1143
- reduction : Optional[str], optional
1144
- The reduction method to apply to the embeddings, by default None.
354
+ if not (0.1 <= temperature <= 2):
355
+ raise InvalidParameterError("The 'temperature' must be between 0.1 and 2.")
356
+ if topk is not None and not (2 <= topk <= 20):
357
+ raise InvalidParameterError("The 'topk' must be between 2 and 20.")
358
+ if topp is not None and not (0 <= topp <= 1):
359
+ raise InvalidParameterError("The 'topp' must be between 0 and 1.")
360
+ if random_seed is not None and not (0 <= random_seed <= 2**32):
361
+ raise InvalidParameterError("The 'random_seed' must be between 0 and 2^32.")
1145
362
 
1146
- Returns
1147
- -------
1148
- SVDModel
1149
- The model with the SVD fit.
1150
- """
1151
- model = self.get_model(model_id)
1152
- return model.fit_svd(
1153
- sequences=sequences,
1154
- n_components=n_components,
1155
- reduction=reduction,
1156
- **kwargs,
1157
- )
363
+ if random_seed is None:
364
+ random_seed = random.randrange(2**32)
1158
365
 
1159
- def get_svd(self, svd_id: str) -> SVDModel:
1160
- """
1161
- Get SVD job results. Including SVD dimension and sequence lengths.
1162
-
1163
- Requires a successful SVD job from fit_svd
1164
-
1165
- Parameters
1166
- ----------
1167
- svd_id : str
1168
- The ID of the SVD job.
1169
- Returns
1170
- -------
1171
- SVDModel
1172
- The model with the SVD fit.
1173
- """
1174
- metadata = svd_get(self.session, svd_id)
1175
- return SVDModel(self.session, metadata)
1176
-
1177
- def __delete_svd(self, svd_id: str) -> bool:
1178
- """
1179
- Delete SVD model.
1180
-
1181
- Parameters
1182
- ----------
1183
- svd_id : str
1184
- The ID of the SVD job.
1185
- Returns
1186
- -------
1187
- bool
1188
- True: successful deletion
1189
-
1190
- """
1191
- return svd_delete(self.session, svd_id)
1192
-
1193
- def list_svd(self) -> List[SVDModel]:
1194
- """
1195
- List SVD models made by user.
1196
-
1197
- Takes no args.
1198
-
1199
- Returns
1200
- -------
1201
- list[SVDModel]
1202
- SVDModels
1203
-
1204
- """
1205
- return [
1206
- SVDModel(self.session, metadata) for metadata in svd_list_get(self.session)
1207
- ]
1208
-
1209
- def __get_svd_results(self, job: Job):
1210
- """
1211
- Get SVD job results. Including SVD dimension and sequence lengths.
1212
-
1213
- Requires a successful SVD job from fit_svd
1214
-
1215
- Parameters
1216
- ----------
1217
- job : Job
1218
- SVD JobFuture
1219
- Returns
1220
- -------
1221
- SVDModel
1222
- The model with the SVD fit.
1223
- """
1224
- return EmbeddingResultFuture(self.session, job)
366
+ body: dict = {
367
+ "generate_n": num_samples,
368
+ "temperature": temperature,
369
+ "maxlen": max_length,
370
+ }
371
+ if topk is not None:
372
+ body["topk"] = topk
373
+ if topp is not None:
374
+ body["topp"] = topp
375
+ if random_seed is not None:
376
+ body["seed"] = random_seed
377
+ if prompt_id is not None:
378
+ body["prompt_id"] = prompt_id
379
+ response = session.post(endpoint, json=body)
380
+ return Job.model_validate(response.json())