aatm 0.1.0__tar.gz

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 (39) hide show
  1. aatm-0.1.0/LICENSE +21 -0
  2. aatm-0.1.0/PKG-INFO +241 -0
  3. aatm-0.1.0/README.md +196 -0
  4. aatm-0.1.0/aatm/__init__.py +3 -0
  5. aatm-0.1.0/aatm/aio/__init__.py +0 -0
  6. aatm-0.1.0/aatm/aio/selectors.py +173 -0
  7. aatm-0.1.0/aatm/aio/translators.py +79 -0
  8. aatm-0.1.0/aatm/api/__init__.py +0 -0
  9. aatm-0.1.0/aatm/api/config.py +68 -0
  10. aatm-0.1.0/aatm/api/data_models.py +85 -0
  11. aatm-0.1.0/aatm/api/main.py +160 -0
  12. aatm-0.1.0/aatm/data_models.py +921 -0
  13. aatm-0.1.0/aatm/debug.py +91 -0
  14. aatm-0.1.0/aatm/embedding_functions.py +290 -0
  15. aatm-0.1.0/aatm/extractors.py +199 -0
  16. aatm-0.1.0/aatm/local_database_utils.py +334 -0
  17. aatm-0.1.0/aatm/logs.py +111 -0
  18. aatm-0.1.0/aatm/main.py +658 -0
  19. aatm-0.1.0/aatm/omop/__init__.py +4 -0
  20. aatm-0.1.0/aatm/omop/condition_occurrence.py +227 -0
  21. aatm-0.1.0/aatm/omop/device_exposure.py +149 -0
  22. aatm-0.1.0/aatm/omop/drug_exposure.py +249 -0
  23. aatm-0.1.0/aatm/omop/registry.py +23 -0
  24. aatm-0.1.0/aatm/pipeline.py +78 -0
  25. aatm-0.1.0/aatm/prompt_helpers.py +48 -0
  26. aatm-0.1.0/aatm/registries/__init__.py +0 -0
  27. aatm-0.1.0/aatm/registries/rerankers.py +114 -0
  28. aatm-0.1.0/aatm/registries/retrievers.py +175 -0
  29. aatm-0.1.0/aatm/registries/selectors.py +157 -0
  30. aatm-0.1.0/aatm/registries/translators.py +93 -0
  31. aatm-0.1.0/aatm/rerankers.py +368 -0
  32. aatm-0.1.0/aatm/retrievers.py +200 -0
  33. aatm-0.1.0/aatm/search_ui.py +129 -0
  34. aatm-0.1.0/aatm/selectors.py +448 -0
  35. aatm-0.1.0/aatm/sql_commands.yaml +78 -0
  36. aatm-0.1.0/aatm/terminology_mapper.py +594 -0
  37. aatm-0.1.0/aatm/time.py +18 -0
  38. aatm-0.1.0/aatm/translators.py +294 -0
  39. aatm-0.1.0/pyproject.toml +66 -0
aatm-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Precision Data
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
aatm-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,241 @@
1
+ Metadata-Version: 2.4
2
+ Name: aatm
3
+ Version: 0.1.0
4
+ Summary: Any-to-Any Terminology Mapping (AATM) is a framework for creating mappings between different terminologies or vocabularies. It uses OHDSI standard vocabularies and data models as a basis for mapping, and can be used to create mappings between any two terminologies or vocabularies. AATM is designed to be flexible and extensible, allowing users to create mappings for a wide range of use cases.
5
+ Author: Vinicius Anjos de Almeida
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Dist: chromadb>=1.4.1
9
+ Requires-Dist: datasets>=2.14.4
10
+ Requires-Dist: dvc[gs]>=3.64.2
11
+ Requires-Dist: dvclive>=3.49.0
12
+ Requires-Dist: fastapi[standard]>=0.136.0
13
+ Requires-Dist: gdown>=5.2.0
14
+ Requires-Dist: google-genai[aiohttp]>=1.60.0
15
+ Requires-Dist: ipykernel>=6.30.1
16
+ Requires-Dist: ipywidgets>=8.1.8
17
+ Requires-Dist: jsonlines>=4.0.0
18
+ Requires-Dist: matplotlib>=3.10.8
19
+ Requires-Dist: mkdocs>=1.6.1
20
+ Requires-Dist: mkdocs-glightbox>=0.5.2
21
+ Requires-Dist: mkdocs-material>=9.7.6
22
+ Requires-Dist: mkdocstrings[python]>=1.0.3
23
+ Requires-Dist: nvidia-ml-py>=13.590.48
24
+ Requires-Dist: openai>=2.16.0
25
+ Requires-Dist: pandas>=2.3.1
26
+ Requires-Dist: peft>=0.18.0
27
+ Requires-Dist: python-multipart>=0.0.26
28
+ Requires-Dist: pyyaml>=6.0.3
29
+ Requires-Dist: questionary>=2.1.1
30
+ Requires-Dist: rank-bm25>=0.2.2
31
+ Requires-Dist: rich>=14.3.1
32
+ Requires-Dist: sentence-transformers>=5.2.2
33
+ Requires-Dist: streamlit>=1.54.0
34
+ Requires-Dist: torch>=2.10.0
35
+ Requires-Dist: torchvision>=0.25.0
36
+ Requires-Dist: tqdm>=4.66.5
37
+ Requires-Dist: transformers>=4.57.3
38
+ Requires-Dist: typer>=0.21.1
39
+ Requires-Python: >=3.12
40
+ Project-URL: Homepage, https://precisiondata.github.io/aatm/
41
+ Project-URL: Documentation, https://precisiondata.github.io/aatm/
42
+ Project-URL: Source, https://github.com/precisiondata/aatm
43
+ Project-URL: Precision Data, https://www.precisiondata.ai/
44
+ Description-Content-Type: text/markdown
45
+
46
+ # Any-to-Any Terminology Mapping
47
+
48
+ **Any-to-Any Terminology Mapping** is an open-source Python framework designed to facilitate terminology mapping tasks. The library organizes this process in a modular and extensible way to support multiple use cases and incorporate new techniques as they emerge.
49
+
50
+ In simple terms, mapping a new expression to a specific terminology involves considering many possible expressions, retrieving the best candidate target terms, and selecting them manually, which can be effortful and time-consuming.
51
+
52
+ AATM leverages the [OMOP vocabularies](https://athena.ohdsi.org/search-terms/start) to facilitate this task. These vocabularies reflect large, community-driven mapping efforts that connect many different health-related terminologies and classifications worldwide and organize them around standard terminologies, which serve as the central connecting nodes in the system. As these mapping efforts continue, healthcare-related concepts become increasingly well represented in these vocabularies, creating a virtuous cycle and increasing the chances of finding a strong correspondence for a new unmapped expression.
53
+
54
+ <p align="center">
55
+ <img src="https://github.com/precisiondata/aatm/blob/main/docs/assets/std_vocabs_diagram.png?raw=true" alt="Standard vocabularies">
56
+ </p>
57
+
58
+ To accomplish this, AATM organizes the mapping process into very simple steps:
59
+
60
+ - **translation**, which can be optional;
61
+ - **retrieval**, which explores what is available from prior mapping efforts; and
62
+ - **selection**, which connects a standard concept to the new expression being mapped.
63
+
64
+ Once this connection is made, every link associated with that standard concept becomes immediately available, enabling mapping to many different terminologies and classifications that are already connected to that concept, effectively breaking down barriers to interoperability in healthcare.
65
+
66
+ ![Terminology mapping pipeline](https://github.com/precisiondata/aatm/blob/main/docs/assets/aatm-pipeline-diagram.jpg?raw=true)
67
+
68
+
69
+ ## Documentation
70
+
71
+ The full documentation is available at: https://precisiondata.github.io/aatm
72
+
73
+
74
+ ## Installation
75
+
76
+
77
+ Install the package in your environment.
78
+
79
+ ```bash
80
+ pip install aatm
81
+ ```
82
+
83
+ If you want to build from the source, clone the repository and install it locally:
84
+
85
+ ```bash
86
+ git clone https://github.com/precisiondata/aatm.git
87
+ pip install -e .
88
+ ```
89
+
90
+ ```bash
91
+ git clone https://github.com/precisiondata/aatm.git
92
+ uv sync
93
+ ```
94
+
95
+ ## 1. Prepare your OMOP vocabularies directory
96
+
97
+ Before running `aatm init`, download the OMOP vocabularies you want to use and place them in a directory. You can find them at https://athena.ohdsi.org/vocabulary/list
98
+
99
+ By default, the CLI expects it at the root directory:
100
+
101
+ ```text
102
+ ./vocabularies
103
+ ```
104
+
105
+ If you do not use that location, you can point the CLI to a different directory with the option `--vocab-dir` or `-vd`. The CLI validates this path during initialization.
106
+
107
+ ---
108
+
109
+ ## 2. Run the initialization command
110
+
111
+ The `init` command is the main CLI setup workflow.
112
+
113
+ It does all of the following for you:
114
+
115
+ - creates the local `.aatm` helper directory where the local databases and aatm config files will be stored
116
+ - ensures `.aatm` is added to `.gitignore`
117
+ - builds the local OMOP SQLite database
118
+ - lets you choose an embedding model
119
+ - lets you choose the standard vocabularies
120
+ - builds the mapping datasets
121
+ - builds the local vector database
122
+
123
+ That means you do **not** need to call Python setup functions manually for the normal setup flow. At the end, you will be ready to run terminology mapping tasks.
124
+
125
+ ### Simplest setup
126
+
127
+ ```bash
128
+ aatm init
129
+ ```
130
+
131
+ This uses the default vocab directory and interactively asks you to choose the embedding model, standard vocabularies and other options.
132
+
133
+ ### Setup with a custom vocab directory
134
+
135
+ ```bash
136
+ aatm init --vocab-dir ./my_vocabularies
137
+ ```
138
+
139
+ ### Setup with an explicit embedding model
140
+
141
+ ```bash
142
+ aatm init --embedding-model embeddinggemma-300M
143
+ ```
144
+
145
+ ### Setup with explicit standard vocabularies
146
+
147
+ ```bash
148
+ aatm init --standard-vocabs LOINC --standard-vocabs SNOMED --standard-vocabs RxNorm
149
+ ```
150
+
151
+ ### Fully explicit setup
152
+
153
+ ```bash
154
+ aatm init \
155
+ --vocab-dir ./vocabularies \
156
+ --embedding-model embeddinggemma-300M \
157
+ --standard-vocabs LOINC \
158
+ --standard-vocabs SNOMED \
159
+ --standard-vocabs RxNorm
160
+ ```
161
+
162
+ ## 3. Prepare your input CSV
163
+
164
+ After initialization, prepare the CSV you want to map.
165
+
166
+ The mapper expects an OMOP-style `SOURCE_TO_CONCEPT_MAP` input structure, including these columns:
167
+
168
+ - `source_code`
169
+ - `source_concept_id`
170
+ - `source_vocabulary_id`
171
+ - `source_code_description`
172
+ - `valid_start_date`
173
+ - `valid_end_date`
174
+ - `invalid_reason`
175
+
176
+ Example:
177
+
178
+ ```csv
179
+ source_code,source_concept_id,source_vocabulary_id,source_code_description,valid_start_date,valid_end_date,invalid_reason
180
+ A01,,LOCAL,"Dor no peito",2020-01-01,2099-12-31,
181
+ B02,,LOCAL,"Diabetes mellitus tipo 2",2020-01-01,2099-12-31,
182
+ ```
183
+
184
+ ---
185
+
186
+ ## 4. Run mapping directly from the CLI
187
+
188
+ The `map` command runs a terminology mapping task. You can use it in two ways:
189
+
190
+ - with a task config file
191
+ - with explicit CLI options
192
+
193
+ Both paths are supported directly by the CLI implementation.
194
+
195
+ ### Option A: run from explicit CLI arguments
196
+
197
+ This is the most direct fully-CLI workflow.
198
+
199
+ ```bash
200
+ aatm map \
201
+ --input-file data/source_to_concept_map.csv \
202
+ --output-dir output \
203
+ --translator-id empty-translator \
204
+ --retriever-id embeddinggemma-300M \
205
+ --reranker-id bm25-reranker \
206
+ --selector-id first-result-selector \
207
+ --batch-size 100
208
+ ```
209
+
210
+ #### Run a small test job
211
+
212
+ Use `--limit-to` when you want to test with only a few rows.
213
+
214
+ ```bash
215
+ aatm map \
216
+ --input-file data/source_to_concept_map.csv \
217
+ --output-dir output \
218
+ --translator-id empty-translator \
219
+ --retriever-id embeddinggemma-300M \
220
+ --reranker-id bm25-reranker \
221
+ --selector-id first-result-selector \
222
+ --limit-to 20
223
+ ```
224
+
225
+ #### Apply rate limiting
226
+
227
+ If needed, you can also pass a rate limit:
228
+
229
+ ```bash
230
+ aatm map \
231
+ --input-file data/source_to_concept_map.csv \
232
+ --output-dir output \
233
+ --translator-id gemini-2.5-flash \
234
+ --retriever-id embeddinggemma-300M \
235
+ --reranker-id bm25-reranker \
236
+ --selector-id first-result-selector \
237
+ --batch-size 50 \
238
+ --rate-limit 100
239
+ ```
240
+
241
+ The CLI accepts all of these options directly.
aatm-0.1.0/README.md ADDED
@@ -0,0 +1,196 @@
1
+ # Any-to-Any Terminology Mapping
2
+
3
+ **Any-to-Any Terminology Mapping** is an open-source Python framework designed to facilitate terminology mapping tasks. The library organizes this process in a modular and extensible way to support multiple use cases and incorporate new techniques as they emerge.
4
+
5
+ In simple terms, mapping a new expression to a specific terminology involves considering many possible expressions, retrieving the best candidate target terms, and selecting them manually, which can be effortful and time-consuming.
6
+
7
+ AATM leverages the [OMOP vocabularies](https://athena.ohdsi.org/search-terms/start) to facilitate this task. These vocabularies reflect large, community-driven mapping efforts that connect many different health-related terminologies and classifications worldwide and organize them around standard terminologies, which serve as the central connecting nodes in the system. As these mapping efforts continue, healthcare-related concepts become increasingly well represented in these vocabularies, creating a virtuous cycle and increasing the chances of finding a strong correspondence for a new unmapped expression.
8
+
9
+ <p align="center">
10
+ <img src="https://github.com/precisiondata/aatm/blob/main/docs/assets/std_vocabs_diagram.png?raw=true" alt="Standard vocabularies">
11
+ </p>
12
+
13
+ To accomplish this, AATM organizes the mapping process into very simple steps:
14
+
15
+ - **translation**, which can be optional;
16
+ - **retrieval**, which explores what is available from prior mapping efforts; and
17
+ - **selection**, which connects a standard concept to the new expression being mapped.
18
+
19
+ Once this connection is made, every link associated with that standard concept becomes immediately available, enabling mapping to many different terminologies and classifications that are already connected to that concept, effectively breaking down barriers to interoperability in healthcare.
20
+
21
+ ![Terminology mapping pipeline](https://github.com/precisiondata/aatm/blob/main/docs/assets/aatm-pipeline-diagram.jpg?raw=true)
22
+
23
+
24
+ ## Documentation
25
+
26
+ The full documentation is available at: https://precisiondata.github.io/aatm
27
+
28
+
29
+ ## Installation
30
+
31
+
32
+ Install the package in your environment.
33
+
34
+ ```bash
35
+ pip install aatm
36
+ ```
37
+
38
+ If you want to build from the source, clone the repository and install it locally:
39
+
40
+ ```bash
41
+ git clone https://github.com/precisiondata/aatm.git
42
+ pip install -e .
43
+ ```
44
+
45
+ ```bash
46
+ git clone https://github.com/precisiondata/aatm.git
47
+ uv sync
48
+ ```
49
+
50
+ ## 1. Prepare your OMOP vocabularies directory
51
+
52
+ Before running `aatm init`, download the OMOP vocabularies you want to use and place them in a directory. You can find them at https://athena.ohdsi.org/vocabulary/list
53
+
54
+ By default, the CLI expects it at the root directory:
55
+
56
+ ```text
57
+ ./vocabularies
58
+ ```
59
+
60
+ If you do not use that location, you can point the CLI to a different directory with the option `--vocab-dir` or `-vd`. The CLI validates this path during initialization.
61
+
62
+ ---
63
+
64
+ ## 2. Run the initialization command
65
+
66
+ The `init` command is the main CLI setup workflow.
67
+
68
+ It does all of the following for you:
69
+
70
+ - creates the local `.aatm` helper directory where the local databases and aatm config files will be stored
71
+ - ensures `.aatm` is added to `.gitignore`
72
+ - builds the local OMOP SQLite database
73
+ - lets you choose an embedding model
74
+ - lets you choose the standard vocabularies
75
+ - builds the mapping datasets
76
+ - builds the local vector database
77
+
78
+ That means you do **not** need to call Python setup functions manually for the normal setup flow. At the end, you will be ready to run terminology mapping tasks.
79
+
80
+ ### Simplest setup
81
+
82
+ ```bash
83
+ aatm init
84
+ ```
85
+
86
+ This uses the default vocab directory and interactively asks you to choose the embedding model, standard vocabularies and other options.
87
+
88
+ ### Setup with a custom vocab directory
89
+
90
+ ```bash
91
+ aatm init --vocab-dir ./my_vocabularies
92
+ ```
93
+
94
+ ### Setup with an explicit embedding model
95
+
96
+ ```bash
97
+ aatm init --embedding-model embeddinggemma-300M
98
+ ```
99
+
100
+ ### Setup with explicit standard vocabularies
101
+
102
+ ```bash
103
+ aatm init --standard-vocabs LOINC --standard-vocabs SNOMED --standard-vocabs RxNorm
104
+ ```
105
+
106
+ ### Fully explicit setup
107
+
108
+ ```bash
109
+ aatm init \
110
+ --vocab-dir ./vocabularies \
111
+ --embedding-model embeddinggemma-300M \
112
+ --standard-vocabs LOINC \
113
+ --standard-vocabs SNOMED \
114
+ --standard-vocabs RxNorm
115
+ ```
116
+
117
+ ## 3. Prepare your input CSV
118
+
119
+ After initialization, prepare the CSV you want to map.
120
+
121
+ The mapper expects an OMOP-style `SOURCE_TO_CONCEPT_MAP` input structure, including these columns:
122
+
123
+ - `source_code`
124
+ - `source_concept_id`
125
+ - `source_vocabulary_id`
126
+ - `source_code_description`
127
+ - `valid_start_date`
128
+ - `valid_end_date`
129
+ - `invalid_reason`
130
+
131
+ Example:
132
+
133
+ ```csv
134
+ source_code,source_concept_id,source_vocabulary_id,source_code_description,valid_start_date,valid_end_date,invalid_reason
135
+ A01,,LOCAL,"Dor no peito",2020-01-01,2099-12-31,
136
+ B02,,LOCAL,"Diabetes mellitus tipo 2",2020-01-01,2099-12-31,
137
+ ```
138
+
139
+ ---
140
+
141
+ ## 4. Run mapping directly from the CLI
142
+
143
+ The `map` command runs a terminology mapping task. You can use it in two ways:
144
+
145
+ - with a task config file
146
+ - with explicit CLI options
147
+
148
+ Both paths are supported directly by the CLI implementation.
149
+
150
+ ### Option A: run from explicit CLI arguments
151
+
152
+ This is the most direct fully-CLI workflow.
153
+
154
+ ```bash
155
+ aatm map \
156
+ --input-file data/source_to_concept_map.csv \
157
+ --output-dir output \
158
+ --translator-id empty-translator \
159
+ --retriever-id embeddinggemma-300M \
160
+ --reranker-id bm25-reranker \
161
+ --selector-id first-result-selector \
162
+ --batch-size 100
163
+ ```
164
+
165
+ #### Run a small test job
166
+
167
+ Use `--limit-to` when you want to test with only a few rows.
168
+
169
+ ```bash
170
+ aatm map \
171
+ --input-file data/source_to_concept_map.csv \
172
+ --output-dir output \
173
+ --translator-id empty-translator \
174
+ --retriever-id embeddinggemma-300M \
175
+ --reranker-id bm25-reranker \
176
+ --selector-id first-result-selector \
177
+ --limit-to 20
178
+ ```
179
+
180
+ #### Apply rate limiting
181
+
182
+ If needed, you can also pass a rate limit:
183
+
184
+ ```bash
185
+ aatm map \
186
+ --input-file data/source_to_concept_map.csv \
187
+ --output-dir output \
188
+ --translator-id gemini-2.5-flash \
189
+ --retriever-id embeddinggemma-300M \
190
+ --reranker-id bm25-reranker \
191
+ --selector-id first-result-selector \
192
+ --batch-size 50 \
193
+ --rate-limit 100
194
+ ```
195
+
196
+ The CLI accepts all of these options directly.
@@ -0,0 +1,3 @@
1
+ from .logs import configure_logging
2
+
3
+ configure_logging()
File without changes
@@ -0,0 +1,173 @@
1
+ import asyncio
2
+ from typing import List
3
+ import dotenv
4
+ from openai import AsyncOpenAI
5
+ from google.genai import types
6
+
7
+ from aatm.data_models import (
8
+ EmptySelectionMetadata,
9
+ RetrieverResults,
10
+ SelectedExpressionMetadata,
11
+ SelectedResult,
12
+ SelectorResults,
13
+ )
14
+ from aatm.prompt_helpers import format_prompt
15
+ from aatm.selectors import OpenAILLMSelector, GeminiLLMSelector
16
+ from aatm.debug import DebugMode, get_debug_mode
17
+ from aatm.logs import get_logger
18
+
19
+ # Load environment variables
20
+ dotenv.load_dotenv()
21
+
22
+ logger = get_logger(__name__)
23
+ debug_mode = get_debug_mode()
24
+
25
+
26
+ class AsyncOpenAILLMSelector(OpenAILLMSelector):
27
+ def __init__(
28
+ self,
29
+ *args,
30
+ **kwargs,
31
+ ):
32
+ super().__init__(*args, **kwargs)
33
+ self.client = AsyncOpenAI()
34
+
35
+ async def select(self, results: RetrieverResults) -> SelectorResults:
36
+ selector_results = SelectorResults(results=[], queries=results.queries)
37
+ async with asyncio.TaskGroup() as tg:
38
+ tasks = []
39
+ for query_id, query in enumerate(results.queries):
40
+ prompt = format_prompt(
41
+ self.prompt_template,
42
+ {
43
+ "json_format": SelectedResult.model_json_schema(),
44
+ "query": query.capitalize(), # avoid case sensitivity for some queries like 'cough' and 'Cough'
45
+ "expressions": [
46
+ r.to_prompt_object() for r in results.results[query_id]
47
+ ],
48
+ },
49
+ )
50
+
51
+ tasks.append(
52
+ tg.create_task(
53
+ self.client.responses.parse(
54
+ model=self.model_id,
55
+ input=prompt,
56
+ text_format=SelectedResult,
57
+ )
58
+ )
59
+ )
60
+
61
+ responses = [t.result() for t in tasks]
62
+
63
+ for response, (query_id, query) in zip(responses, enumerate(results.queries)):
64
+ selected_result: SelectedResult = response.output_parsed
65
+ assert isinstance(selected_result, SelectedResult), (
66
+ f"Expected SelectedResult object from OpenAI, but got {type(selected_result)}"
67
+ )
68
+
69
+ # case where no expression is selected
70
+ if selected_result.expression_id is None:
71
+ selector_results.results.append(EmptySelectionMetadata())
72
+ continue
73
+
74
+ # case where expression is selected but it is not in the results
75
+ results_expression_ids = set(
76
+ [r.expression_id for r in results.results[query_id]]
77
+ )
78
+
79
+ if selected_result.expression_id not in results_expression_ids:
80
+ selector_results.results.append(EmptySelectionMetadata())
81
+ continue
82
+
83
+ # case where expression is selected and it is in the results
84
+ for result_idx, r in enumerate(results.results[query_id]):
85
+ if r.expression_id == selected_result.expression_id:
86
+ selector_results.results.append(
87
+ SelectedExpressionMetadata(
88
+ **r.model_dump(), result_list_index=result_idx
89
+ )
90
+ )
91
+ break
92
+
93
+ return selector_results
94
+
95
+
96
+ class AsyncGeminiLLMSelector(GeminiLLMSelector):
97
+ async def select(self, results: RetrieverResults) -> SelectorResults:
98
+ selector_results = SelectorResults(results=[], queries=results.queries)
99
+ async with asyncio.TaskGroup() as tg:
100
+ tasks = []
101
+ for query_id, query in enumerate(results.queries):
102
+ prompt = format_prompt(
103
+ self.prompt_template,
104
+ {
105
+ "json_format": SelectedResult.model_json_schema(),
106
+ "query": query.capitalize(), # avoid case sensitivity for some queries like 'cough' and 'Cough'
107
+ "expressions": [
108
+ r.to_prompt_object() for r in results.results[query_id]
109
+ ],
110
+ },
111
+ )
112
+
113
+ gemini_formatted_prompt = []
114
+ for msg in prompt:
115
+ gemini_formatted_prompt.append(types.UserContent(msg["content"]))
116
+
117
+ if debug_mode == DebugMode.GEMINI_LLM_SELECTOR:
118
+ logger.debug(prompt)
119
+ logger.debug(gemini_formatted_prompt)
120
+
121
+ tasks.append(
122
+ tg.create_task(
123
+ self.client.aio.models.generate_content(
124
+ model=self.model_id,
125
+ contents=gemini_formatted_prompt,
126
+ config=types.GenerateContentConfig(
127
+ response_mime_type="application/json",
128
+ response_schema=SelectedResult,
129
+ ),
130
+ )
131
+ )
132
+ )
133
+
134
+ responses: List[types.GenerateContentResponse] = [t.result() for t in tasks]
135
+ for response, (query_id, query) in zip(responses, enumerate(results.queries)):
136
+ selected_result: SelectedResult = SelectedResult.model_validate_json(
137
+ response.text
138
+ )
139
+
140
+ if debug_mode == DebugMode.GEMINI_LLM_SELECTOR:
141
+ logger.debug(response)
142
+ logger.debug(response.text)
143
+ logger.debug(SelectedResult.model_validate_json(response.text))
144
+
145
+ assert isinstance(selected_result, SelectedResult), (
146
+ f"Expected SelectedResult object from Gemini, but got {type(selected_result)}"
147
+ )
148
+
149
+ # case where no expression is selected
150
+ if selected_result.expression_id is None:
151
+ selector_results.results.append(EmptySelectionMetadata())
152
+ continue
153
+
154
+ # case where expression is selected but it is not in the results
155
+ results_expression_ids = set(
156
+ [r.expression_id for r in results.results[query_id]]
157
+ )
158
+
159
+ if selected_result.expression_id not in results_expression_ids:
160
+ selector_results.results.append(EmptySelectionMetadata())
161
+ continue
162
+
163
+ # case where expression is selected and it is in the results
164
+ for result_idx, r in enumerate(results.results[query_id]):
165
+ if r.expression_id == selected_result.expression_id:
166
+ selector_results.results.append(
167
+ SelectedExpressionMetadata(
168
+ **r.model_dump(), result_list_index=result_idx
169
+ )
170
+ )
171
+ break
172
+
173
+ return selector_results