-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
4236 lines (3634 loc) · 141 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import cProfile
import csv
import datetime
import itertools
import json
import logging
import math
import os
import pstats
import re
import sqlite3
import sys
import unittest
from abc import ABC, abstractmethod
from collections import Counter
from dataclasses import dataclass
from functools import wraps
from typing import (
Any,
Callable,
Coroutine,
Iterable,
Literal,
Mapping,
Self,
TypeAlias,
TypeVar,
Union,
)
import httpx
import openai
import pandas as pd
import pydantic
import tenacity
import webbrowser
from frozendict import frozendict
import qasync
from PyQt6 import QtCore, QtGui, QtWidgets
# Optional imports
## dotenv
try:
import dotenv
except ImportError:
logging.info(
"python-dotenv package not installed. "
"Relying on explicit environment variables"
)
dotenv = None
## tiktoken
try:
import tiktoken
except ImportError:
logging.warning(
"tiktoken package is not installed. "
"Will not be able to use track token usage"
)
tiktoken = None
# Boilerplate
## Typing
class BranchPath(str):
"""Snowstorm working branch"""
class SCTID(int):
"""SNOMED CT identifier"""
class SCTDescription(str):
"""Any of valid SNOMED CT descriptions
Prefer PT for LLMs and FSN for humans.
"""
class ECLExpression(str):
"""Expression Constraint Language expression"""
class SCGExpression(str):
"""SNOMED CT Compositional Grammar expression"""
class EscapeHatch(object):
"""\
"Escape hatch" sentinel type for prompters
Escape hatch is provided to an LLM agent to be able to choose nothing rather
than hallucinating an answer. Will have just one singleton instance.
"""
WORD: SCTDescription = SCTDescription("[NONE]")
def __str__(self) -> str:
return self.WORD
class BooleanAnswer(str):
"""\
Boolean answer constants for prompters for yes/no questions
"""
YES = SCTDescription("[AYE]")
NO = SCTDescription("[NAY]")
def __new__(cls, value: bool):
return cls.YES if value else cls.NO
PrompterOption: TypeAlias = Literal["human", "openai", "azure"]
JsonPrimitive: TypeAlias = int | float | str | bool | None
Json: TypeAlias = dict[str, "Json"] | list["Json"] | JsonPrimitive
JsonDict: TypeAlias = dict[str, Json]
OpenAIPromptRole: TypeAlias = Literal["user", "system", "assisstant"]
OpenAIMessages: TypeAlias = tuple[frozendict[OpenAIPromptRole, str]]
OutFormat: TypeAlias = Literal["SCG", "CRS", "JSON"]
T = TypeVar("T")
Url = str
## Logging
LOGGER = logging.getLogger("Bouzyges")
logging.basicConfig(level=logging.INFO)
LOGGER.info("Logging started")
# Default handler and formatter
LOGGER.handlers.clear()
_stdout_handler = logging.StreamHandler(sys.stdout)
_formatter = logging.Formatter(
"[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] "
"%(message)s"
)
_stdout_handler.setFormatter(_formatter)
LOGGER.addHandler(_stdout_handler)
LOGGER.info("Logging configured")
## Request retrying decorators
def log_retry_error(state: tenacity.RetryCallState) -> None:
result = state.outcome
if result and result.failed:
exception = result.exception()
LOGGER.error(f"Retry failed: {result}", exc_info=exception)
retry_exponential = tenacity.retry(
wait=tenacity.wait_random_exponential(multiplier=1, max=60),
retry_error_callback=log_retry_error,
)
retry_fixed = tenacity.retry(
wait=tenacity.wait_fixed(15),
stop=tenacity.stop_never,
retry_error_callback=log_retry_error,
)
## Parameters
# Load environment variables for API access
if dotenv is not None:
LOGGER.info("Loading environment variables from .env")
if os.path.exists(".env"):
dotenv.load_dotenv()
else:
LOGGER.warning("No .env file found")
DEFAULT_MODEL = "gpt-4o-mini"
AVAILABLE_PROMPTERS: dict[PrompterOption, str] = {
"openai": "OpenAI",
"azure": "Azure OpenAI",
"human": "Human",
}
CSV_SEPARATORS: dict[str, str] = {
",": ",",
";": ";",
"Tab": "\t",
}
QUOTECHARS: list[str] = ['"', "'"]
QUOTING_POLICY: dict[int, str] = {
csv.QUOTE_MINIMAL: "Quote minimal",
csv.QUOTE_ALL: "Quote all",
csv.QUOTE_NONNUMERIC: "Quote string",
csv.QUOTE_NONE: "No quoting",
}
class ProfilingParameters(pydantic.BaseModel):
"""\
Parameters to control profiling of the program.
"""
enabled: bool
stop_profiling_after_seconds: int | None
class LoggingParameters(pydantic.BaseModel):
"""\
Parameters to control logging.
"""
log_to_file: bool
logging_level: int
def update(self, level):
self.logging_level = level
LOGGER.setLevel(level=self.logging_level)
class APIParameters(pydantic.BaseModel):
"""\
Parameters to control the interface to Snowstorm, cache and LLMs.
"""
prompter: PrompterOption
repeat_prompts: int | None
snowstorm_url: Url
llm_model_id: str
cache_db: str | None
max_concurrent_workers: int
class EnvironmentParameters(pydantic.BaseModel):
"""\
Parameters that reflect the environment variables.
"""
OPENAI_API_KEY: str | None = None
AZURE_API_KEY: str | None = None
AZURE_API_ENDPOINT: str | None = None
def fill_from_env(self) -> None:
for env in self.model_fields:
env_value = os.getenv(env)
setattr(self, env, env_value or None)
class IOParameters(pydantic.BaseModel):
"""\
Parameters for reading and writing CSV file data.
"""
file: str
sep: str
quotechar: str
quoting: int
class IOParametersWidget(QtWidgets.QWidget):
def __init__(self, par: IOParameters, name: str, *args, **kwargs) -> None:
# Add pydantic fields
super().__init__(*args, **kwargs)
self.logger = LOGGER.getChild(name)
self.parameters: IOParameters = par
self._populate_layout()
self.set_values()
def _populate_layout(self) -> None:
layout = QtWidgets.QHBoxLayout()
self.sep_cb = QtWidgets.QComboBox()
self.sep_cb.addItems(map(lambda s: "Separator: " + s, CSV_SEPARATORS))
self.sep_cb.currentIndexChanged.connect(self.separator_changed)
layout.addWidget(self.sep_cb)
self.quoting_cb = QtWidgets.QComboBox()
self.quoting_cb.addItems(QUOTING_POLICY.values())
self.quoting_cb.currentIndexChanged.connect(self.quoting_policy_changed)
layout.addWidget(self.quoting_cb)
qchar_label = QtWidgets.QLabel("Quote character:")
layout.addWidget(qchar_label)
self.qc_edit = QtWidgets.QLineEdit()
self.qc_edit.setPlaceholderText('"')
self.qc_edit.setMaximumWidth(30)
self.qc_edit.textChanged.connect(self.quote_char_changed)
layout.addWidget(self.qc_edit)
spacer = QtWidgets.QSpacerItem(
40,
20,
QtWidgets.QSizePolicy.Policy.Expanding,
QtWidgets.QSizePolicy.Policy.Minimum,
)
layout.addItem(spacer)
self.setLayout(layout)
def separator_changed(self, index) -> None:
self.parameters.sep = list(CSV_SEPARATORS)[index]
self.logger.debug(f"Separator changed to: {self.parameters.sep}")
def quoting_policy_changed(self, index) -> None:
self.parameters.quoting = list(QUOTING_POLICY)[index]
self.logger.debug(
f"Quoting policy changed to: {self.parameters.quoting}:"
f"{QUOTING_POLICY[self.parameters.quoting]}"
)
self.qc_edit.setEnabled(self.parameters.quoting != csv.QUOTE_NONE)
def quote_char_changed(self, text) -> None:
self.parameters.quotechar = text
self.logger.debug(f"Quote character changed to: {repr(text)}")
def update_file(
self, file: str, update: Callable[[str], None] | None = None
) -> None:
self.parameters.file = file
if update:
update(file)
self.logger.debug(f"Input file set to: {file}")
def set_values(self) -> None:
idx = list(CSV_SEPARATORS).index(self.parameters.sep)
self.sep_cb.setCurrentIndex(idx)
self.quoting_cb.setCurrentIndex(
list(QUOTING_POLICY).index(self.parameters.quoting)
)
self.qc_edit.setText(self.parameters.quotechar)
self.qc_edit.setEnabled(self.parameters.quoting != csv.QUOTE_NONE)
class RunParameters(pydantic.BaseModel):
"""\
Parameters for the run of the program.
"""
api: APIParameters
env: EnvironmentParameters = pydantic.Field(
exclude=True, default_factory=EnvironmentParameters
)
log: LoggingParameters
prof: ProfilingParameters
read: IOParameters
write: IOParameters
format: OutFormat
out_dir: str = pydantic.Field(default_factory=os.getcwd)
@classmethod
def from_file(cls, file: str) -> RunParameters:
with open(file, "r") as f:
json_data = json.load(f)
params = RunParameters(**json_data)
# Environment variables are not stored in JSON
params.env.fill_from_env()
return params
def update(self, json_data: dict) -> None:
self.__init__(**json_data)
self.log.update(self.log.logging_level)
def save(self, file: str) -> None:
with open(file, "w") as f:
json.dump(self.model_dump(), f, indent=2)
PARAMS = RunParameters.from_file("default_config.json")
LOGGER.info(f"Parameters loaded: {json.dumps(PARAMS.model_dump(), indent=2)}")
LOGGER.setLevel(PARAMS.log.logging_level)
## Logic constants
### MRCM
MRCM_DOMAIN_REFERENCE_SET_ECL = ECLExpression("<<723589008")
WHITELISTED_SUPERTYPES: set[SCTID] = {
# Only limit to well-modeled supertypes for now
SCTID(404684003), # Clinical finding
SCTID(71388002), # Procedure
}
### Escape hatch sentinel
NULL_ANSWER = EscapeHatch()
### "Is a" relationships
IS_A = SCTID(116680003)
### SNOMED root concept
ROOT_CONCEPT = SCTID(138875005)
### Temporary substitute for reading from a file
TERMS = ["Pyogenic abscess of liver", "Invasive lobular carcinoma of breast"]
### Default prompt repetition count
DEFAULT_REPEAT_PROMPTS: int | None = 3
## Dataclasses
### SNOMED modelling
@dataclass(frozen=True, slots=True)
class AttributeRelationship:
"""Represents a SNOMED CT attribute-value pair relationship."""
attribute: SCTID
value: SCTID
@dataclass(frozen=True, slots=True)
class AttributeGroup:
"""Represents a SNOMED CT attribute group."""
relationships: frozenset[AttributeRelationship]
@dataclass(frozen=True, slots=True)
class Concept:
"""Represents a SNOMED CT concept."""
sctid: SCTID
pt: SCTDescription
fsn: SCTDescription
groups: frozenset[AttributeGroup]
ungrouped: frozenset[AttributeRelationship]
defined: bool
@classmethod
def from_rela_json(cls, relationship_data: list[dict]):
# Get concept proper info
# Everyone is expected to have at least an 'Is a' relationship
# Except root, but encountering it is an error
if len(relationship_data) == 0:
raise ValueError("No relationships found; could it be a root?")
specimen = relationship_data[0]["source"]
sctid = SCTID(specimen["conceptId"])
pt = SCTDescription(specimen["pt"]["term"])
fsn = SCTDescription(specimen["fsn"]["term"])
defined = specimen["definitionStatus"] == "FULLY_DEFINED"
# Get relationships
groups: dict[int, set[AttributeRelationship]] = {}
ungrouped: set[AttributeRelationship] = set()
for relationship in relationship_data:
attribute = SCTID(relationship["type"]["conceptId"])
# Skip 'Is a' relationships here
if attribute == IS_A:
continue
value = SCTID(relationship["target"]["conceptId"])
group = relationship["groupId"]
rel = AttributeRelationship(attribute, value)
if group == 0:
ungrouped.add(rel)
else:
groups.setdefault(group, set()).add(rel)
return cls(
sctid=sctid,
pt=pt,
fsn=fsn,
groups=frozenset(
AttributeGroup(frozenset(relationships))
for relationships in groups.values()
),
ungrouped=frozenset(ungrouped),
defined=defined,
)
@classmethod
def from_json(cls, json_data: dict):
groups: dict[int, set[AttributeRelationship]] = {}
ungrouped: set[AttributeRelationship] = set()
for relationship in json_data["relationships"]:
if not relationship["active"]:
continue
attribute = SCTID(relationship["type"]["conceptId"])
# Skip 'Is a' relationships here
if attribute == IS_A:
continue
value = SCTID(relationship["target"]["conceptId"])
rel = AttributeRelationship(attribute, value)
if (group := relationship["groupId"]) == 0:
ungrouped.add(rel)
else:
groups.setdefault(group, set()).add(rel)
match json_data["definitionStatus"]:
case "FULLY_DEFINED":
defined = True
case "PRIMITIVE":
defined = False
case _:
raise (ValueError("Unknown definition status"))
return cls(
sctid=SCTID(json_data["conceptId"]),
pt=SCTDescription(json_data["pt"]["term"]),
fsn=SCTDescription(json_data["fsn"]["term"]),
groups=frozenset(
AttributeGroup(frozenset(relationships))
for relationships in groups.values()
),
ungrouped=frozenset(ungrouped),
defined=defined,
)
@dataclass(frozen=True, slots=True)
class MRCMDomainRefsetEntry:
"""\
Represents an entry in the MRCM domain reference set.
Used mainly to obtain an entry ancestor anchor for a semantic portrait. Contains
more useful information for domain modelling, but it is not yet well explored.
"""
# Concept properties
sctid: SCTID
term: SCTDescription
# Additional fields
domain_constraint: ECLExpression
guide_link: Url # For eventual RAG connection
# Currently uses unparseable extension of ECL grammar,
# but one day we will use it
domain_template: ECLExpression
parent_domain: ECLExpression | None = None
proximal_primitive_refinement: ECLExpression | None = None
@classmethod
def from_json(cls, json_data: dict):
af = json_data["additionalFields"]
dom = af.get("parentDomain")
prf = af.get("proximalPrimitiveRefinement")
return cls(
sctid=SCTID(json_data["referencedComponent"]["conceptId"]),
term=SCTDescription(json_data["referencedComponent"]["pt"]["term"]),
domain_template=ECLExpression(
# Use precoordination: stricter
af["domainTemplateForPrecoordination"]
),
domain_constraint=ECLExpression(af["domainConstraint"]),
guide_link=Url(af["guideURL"]),
parent_domain=ECLExpression(dom) if dom else None,
proximal_primitive_refinement=ECLExpression(prf) if prf else None,
)
# Solving for presence vs. absence of attributes is way, way easier than solving
# quantitative problems. For now, Cardinality will likely be ignored.
@dataclass(frozen=True, slots=True)
class Cardinality:
"""\
Represents a cardinality of an attribute in a group or a definition.
"""
min: int
max: None | int
@dataclass(frozen=True, slots=True)
class AttributeDomain:
"""\
Represents a domain of applications of an attribute.
"""
sctid: SCTID
pt: SCTDescription
domain_id: SCTID
grouped: bool
cardinality: Cardinality
in_group_cardinality: Cardinality
@dataclass(frozen=True, slots=True)
class AttributeRange:
"""\
Represents a range of values of an attribute.
"""
sctid: SCTID
pt: SCTDescription
range_constraint: ECLExpression
attribute_rule: ECLExpression
contentType: str
@dataclass(frozen=True, slots=True)
class AttributeConstraints:
"""\
Represents information about an attribute obtained from a known set of parent
concepts.
"""
sctid: SCTID
pt: SCTDescription
attribute_domain: Iterable[AttributeDomain]
# May actually not be required
# because /mrcm/{branch}/attribute-values/ exists
attribute_range: Iterable[AttributeRange]
@classmethod
def from_json(cls, json_data: dict):
return cls(
sctid=SCTID(json_data["conceptId"]),
pt=SCTDescription(json_data["pt"]["term"]),
attribute_domain=[
AttributeDomain(
sctid=SCTID(json_data["conceptId"]),
pt=SCTDescription(json_data["pt"]["term"]),
domain_id=SCTID(ad["domainId"]),
grouped=ad["grouped"],
cardinality=Cardinality(
ad["attributeCardinality"]["min"],
ad["attributeCardinality"].get("max"),
),
in_group_cardinality=Cardinality(
ad["attributeInGroupCardinality"]["min"],
ad["attributeInGroupCardinality"].get("max"),
),
)
for ad in json_data["attributeDomain"]
],
attribute_range=[
AttributeRange(
sctid=SCTID(json_data["conceptId"]),
pt=SCTDescription(json_data["pt"]["term"]),
range_constraint=ECLExpression(ar["rangeConstraint"]),
attribute_rule=ECLExpression(ar["attributeRule"]),
contentType=ar["contentType"],
)
for ar in json_data["attributeRange"]
],
)
### Mutable portrait
@dataclass
class SemanticPortrait:
"""\
Represents an interactively built semantic portrait of a source concept."""
def __init__(
self,
term: str,
context: Iterable[str] | None = None,
metadata: frozendict[str, JsonPrimitive] = frozendict(),
) -> None:
self.source_term: str = term
self.context: Iterable[str] | None = context
self.ancestor_anchors: set[SCTID] = set()
self.unchecked_attributes: set[SCTID] = set()
self.attributes: dict[SCTID, SCTID] = {}
self.rejected_attributes: set[SCTID] = set()
self.rejected_supertypes: set[SCTID] = set()
self.relevant_constraints: dict[SCTID, AttributeConstraints] = {}
self.metadata: frozendict[str, JsonPrimitive] = metadata
def to_scg(self: SemanticPortrait) -> SCGExpression:
"""\
Convert a SemanticPortrait to a SNOMED CT Post-Coordinated Expression
"""
# Always Subtype
prefix = "<<<"
focus_concepts = "+".join(str(a) for a in self.ancestor_anchors)
attributes = ",".join(f"{a}={v}" for a, v in self.attributes.items())
return SCGExpression(
prefix
+ (focus_concepts or str(ROOT_CONCEPT))
+ ":" * bool(attributes)
+ attributes
)
class WrappedResult:
"""\
Represents a completed semantic portrait with additional metadata.
"""
def __init__(
self,
portrait: SemanticPortrait,
name_map: Mapping[SCTID, SCTDescription],
) -> None:
self.portrait: SemanticPortrait = portrait
self.name_map: Mapping[SCTID, SCTDescription] = name_map
## Exceptions
class ProfileMark(Exception):
"""Interrupts flow of the program at arbitrary point for profiling"""
class BouzygesError(Exception):
"""Base class for Bouzyges errors."""
class SnowstormAPIError(Exception):
"""Raised when the Snowstorm API returns a bad response."""
class SnowstormRequestError(SnowstormAPIError):
"""Raised when the Snowstorm API returns a non-200 response"""
def __init__(self, text, response, *_):
super().__init__(text)
self.response = response
@classmethod
def from_response(cls, response):
LOGGER.error(
f"Request: {response.request.method}, {response.request.url}"
)
if response:
LOGGER.error(f"Response: {json.dumps(response.json(), indent=2)}")
return cls(
f"Snowstorm API returned {response.status_code} status code",
response,
)
class PrompterError(Exception):
"""Raised when the prompter encounters an error."""
class PrompterInitError(PrompterError):
"""Raised when prompter can not be initialized"""
## Hacked Httpx client
# HACK: Somehow, for whatever reason, the connection pool of Httpx client
# is constantly filling up with unusable connections. This is a hack to
# flush the pool on a timeout and continue.
class HackedAsyncClient(httpx.AsyncClient):
"""\
Hacked Httpx client to flush connection pool on timeout.
"""
async def send(self, *args, **kwargs):
try:
return await super().send(*args, **kwargs)
except httpx.HTTPError as e:
transport: httpx.AsyncHTTPTransport = self._transport # type: ignore
pool = transport._pool
conns = pool.connections
bad_connections = {
"closed": [],
"expired": [],
"idle": [],
}
for conn in conns:
if conn.is_closed:
bad_connections["closed"].append(conn)
elif conn.has_expired:
bad_connections["expired"].append(conn)
elif conn.is_idle:
bad_connections["idle"].append(conn)
LOGGER.error(
f"Failed to connect: {type(e)}. Flushing connections "
f"from AsyncClient",
exc_info=e,
)
for reason, conns in bad_connections.items():
if not conns:
continue
LOGGER.error(f"{len(conns)} connections to close: {reason}")
await pool._close_connections(conns)
for connection in conns:
pool._connections.remove(connection)
raise
except Exception as e:
LOGGER.error(f"Failed to connect: {type(e)}", exc_info=e)
raise
## Prompt class
@dataclass(frozen=True, slots=True)
class Prompt:
"""\
Represents a prompt for the LLM agent to answer.
Has option to store API parameters for the answer.
"""
prompt_message: str | OpenAIMessages
options: frozenset[SCTDescription] | None = None
escape_hatch: SCTDescription | None = None
api_options: frozendict[str, JsonPrimitive] | None = None
def to_json(self) -> JsonDict:
"""Convert the prompt to a JSON-serializable format for caching."""
if isinstance(self.prompt_message, str):
message = self.prompt_message
else:
message = [
{role: text for role, text in message.items()}
for message in self.prompt_message
]
api_options = dict(self.api_options) if self.api_options else None
return {
"prompt_text": json.dumps(message, sort_keys=True),
"prompt_is_json": not isinstance(self.prompt_message, str),
"api_options": json.dumps(api_options),
} # pyright: ignore[reportReturnType] # Ruff says it's okay
# Logic classes
## Prompt cache interface
class PromptCache:
"""\
Interface for a prompt cache.
Saves prompts and answers to avoid re-prompting the same questions and wasting
tokens.
"""
def __init__(self, db_connection: sqlite3.Connection):
# TODO: form an event queue for this; sqlite does not do well in
# multi-threaded environments
self.connection = db_connection
self.table_name = "prompt"
self.logger = LOGGER.getChild("PromptCache")
# Create the table if it does not exist in DB
table_exists_query = """\
SELECT name
FROM sqlite_master
WHERE type='table' AND name=?;
"""
exists = self.connection.execute(table_exists_query, [self.table_name])
if not exists.fetchone():
self.logger.info("Creating prompt cache table")
with open("init_prompt_cache.sql") as f:
self.connection.executescript(f.read())
self.connection.commit()
else:
self.logger.info("Existing prompt table already exists")
def get(self, model: str, prompt: Prompt, attempt: int) -> str | None:
"""\
Get the answer from the cache for specified model.
"""
prompt_dict = prompt.to_json()
api_are_none = prompt_dict["api_options"] is None
query = f"""
SELECT response
FROM {self.table_name}
WHERE
attempt = ? AND
model = ? AND
prompt_text = ? AND
prompt_is_json = ? AND
api_options {"IS" if api_are_none else "="} ?
"""
try:
cursor = self.connection.cursor()
cursor.execute(
query,
(attempt, model, *prompt_dict.values()),
)
if answer := cursor.fetchone():
return answer[0]
return None
except (sqlite3.InterfaceError, sqlite3.DatabaseError):
self.logger.warning(
"Cache access failed for prompt: "
+ f"{json.dumps(prompt.to_json())}"
)
return None
def remember(
self, model: str, prompt: Prompt, response: str, attempt: int
) -> None:
"""\
Remember the answer for the prompt for the specified model.
"""
query = f"""
INSERT INTO {self.table_name} (
attempt,
model,
prompt_text,
prompt_is_json,
api_options,
response
)
VALUES (?, ?, ?, ?, ?, ?)
"""
# Convert prompt to serializable format
prompt_dict = prompt.to_json()
cursor = self.connection.cursor()
cursor.execute(
query,
(
attempt,
model,
*prompt_dict.values(),
response,
),
)
self.connection.commit()
## Logic prompt format classes
class PromptFormat(ABC):
"""\
Abstract class for formatting prompts for the LLM agent.
"""
ROLE = (
"a domain expert system in clinical terminology who is helping to "
"build a semantic representation of a concept in a clinical ontology "
"by providing information about the concept's relationships to other "
"concepts in the ontology"
)
TASK = (
"to provide information about the given term supertypes, "
"attributes, attribute values, and other relevant information as "
"requested, inferring them only from the term meaning and the provided "
"context"
)
REQUIREMENTS = (
"in addition to providing accurate factually correct information, "
"it is critically important that you provide answer in a "
"format that is requested by the system, as answers will "
"be parsed by a machine. Your answer should ALWAYS end with a line "
"that says 'The answer is ' and the chosen option. This is the second "
"time you are being asked the question, as the first time you failed "
"to adhere to the format. Please make sure to follow the instructions."
)
INSTRUCTIONS = (
"Options that speculate about details not explicitly included in the"
"term meaning are to be avoided, e.g. term 'operation on abdominal "
"region' should NOT be assumed to be a laparoscopic operation, as "
"access method is not specified in the term. It absolutely required to "
"explain your reasoning when providing answers. The automated system "
"will look for the last answer surrounded by square brackets, e.g. "
"[answer], so only one of the options should be selected and returned "
"in this format. If the question looks like 'What is the topography of "
"the pulmonary tuberculosis?', and the options are [Lung structure], "
"[Heart structure], [Kidney structure], the good answer would end with"
"[Lung structure].' Answers that do not include reasoning are "
"unacceptable. Incorrect answers will be penalized: if a source term "
"does contain a specific attribute, you must answer so."
)
ESCAPE_INSTRUCTIONS = (
f" If all provided options are incorrect, or imply extra information "
f"not present explicitly and unambiguously in the term, you must "
f"explain why each option is incorrect, and finalize the answer with "
f"the word {EscapeHatch.WORD}. However, if any of the offered terms "
f"matches the question, you must select it."
)
def __init__(self):
self.logger = LOGGER.getChild("PromptFormat")
@staticmethod
def wrap_term(term: str) -> str:
"""Wrap a term in square brackets."""
return f"[{term}]"
@abstractmethod
def form_supertype(
self,
term: str,
options: Iterable[SCTDescription],
allow_escape: bool = True,
term_context: str | None = None,
options_context: dict[SCTDescription, str] | None = None,
) -> Prompt:
"""\
Format a prompt for the LLM agent to choose the best matching proximal ancestor
for a term.
"""
@abstractmethod
def form_attr_presence(
self,
term: str,
attribute: SCTDescription,
term_context: str | None = None,
attribute_context: str | None = None,
) -> Prompt:
"""\
Format a prompt for the LLM agent to decide if an attribute is present in a
term.
"""
@abstractmethod
def form_attr_value(
self,
term: str,
attribute: SCTDescription,
options: Iterable[SCTDescription],
term_context: str | None = None,
attribute_context: str | None = None,
options_context: dict[SCTDescription, str] | None = None,
allow_escape: bool = True,
) -> Prompt:
"""\