51 | {%- if cell.execution_count is defined -%}
52 | In [{{ cell.execution_count|replace(None, " ") }}]:
53 | {%- else -%}
54 | In [ ]:
55 | {%- endif -%}
56 |
57 | {%- endblock in_prompt %}
58 |
59 | {% block empty_in_prompt -%}
60 |
73 | {%- if output.output_type == 'execute_result' -%}
74 | {%- if cell.execution_count is defined -%}
75 | Out[{{ cell.execution_count|replace(None, " ") }}]:
76 | {%- else -%}
77 | Out[ ]:
78 | {%- endif -%}
79 | {%- endif -%}
80 |
81 | {% endblock output_area_prompt %}
82 |
83 | {% block output %}
84 | {%- if output.output_type == 'execute_result' -%}
85 |
86 | {%- else -%}
87 |
88 | {%- endif -%}
89 | {% if resources.global_content_filter.include_output_prompt %}
90 | {{ self.output_area_prompt() }}
91 | {% endif %}
92 | {{ super() }}
93 |
94 | {% endblock output %}
95 |
96 | {% block markdowncell scoped %}
97 |
116 | {%- endblock markdowncell %}
117 |
118 | {% block rawcell scoped %}
119 | {%- if cell.metadata.get('raw_mimetype', '').lower() in resources.get('raw_mimetypes', ['']) -%}
120 | {{ cell.source | clean_html }}
121 | {%- endif -%}
122 | {%- endblock rawcell %}
123 |
124 | {% block unknowncell scoped %}
125 | unknown type {{ cell.type }}
126 | {% endblock unknowncell %}
127 |
128 | {% block execute_result -%}
129 | {%- set extra_class="jp-OutputArea-executeResult" -%}
130 | {% block data_priority scoped %}
131 | {{ super() }}
132 | {% endblock data_priority %}
133 | {%- set extra_class="" -%}
134 | {%- endblock execute_result %}
135 |
136 | {% block stream_stdout -%}
137 |
138 |
139 | {{- output.text | ansi2html -}}
140 |
141 |
142 | {%- endblock stream_stdout %}
143 |
144 | {% block stream_stderr -%}
145 |
146 |
147 | {{- output.text | ansi2html -}}
148 |
149 |
150 | {%- endblock stream_stderr %}
151 |
152 | {% block stream_stdin -%}
153 | {%- if resources.global_content_filter.include_output_stdin -%}
154 |
155 |
156 | {{- output.text | ansi2html -}}
157 |
158 |
159 | {%- endif %}
160 | {%- endblock stream_stdin %}
161 |
162 | {% block data_svg scoped -%}
163 |
174 | {%- endblock data_svg %}
175 |
176 | {% block data_mermaid scoped -%}
177 |
178 |
179 | {{ output.data['text/vnd.mermaid'].strip() }}
180 |
181 |
182 | {%- endblock data_mermaid %}
183 |
184 | {% block data_html scoped -%}
185 |
192 | {%- endblock data_html %}
193 |
194 | {% block data_markdown scoped -%}
195 | {%- if resources.should_sanitize_html %}
196 | {%- set html_value=output.data['text/markdown'] | markdown2html | clean_html -%}
197 | {%- else %}
198 | {%- set html_value=output.data['text/markdown'] | markdown2html -%}
199 | {%- endif %}
200 |
203 | {%- endblock data_markdown %}
204 |
205 | {% block data_png scoped %}
206 |
233 | {%- endblock data_png %}
234 |
235 | {% block data_jpg scoped %}
236 |
263 | {%- endblock data_jpg %}
264 |
265 | {% block data_latex scoped %}
266 |
269 | {%- endblock data_latex %}
270 |
271 | {% block error -%}
272 |
273 |
274 | {{- super() -}}
275 |
276 |
277 | {%- endblock error %}
278 |
279 | {%- block traceback_line %}
280 | {{ line | ansi2html }}
281 | {%- endblock traceback_line %}
282 |
283 | {%- block data_text scoped %}
284 |
289 | {%- endblock -%}
290 |
291 | {#
292 | ###############################################################################
293 | # TODO: how to better handle JavaScript repr? #
294 | ###############################################################################
295 | #}
296 |
297 | {%- block data_javascript scoped %}
298 | {% set div_id = uuid4() %}
299 |
307 | {%- endblock -%}
308 |
309 | {%- block data_widget_view scoped %}
310 | {% set div_id = uuid4() %}
311 | {% set datatype_list = output.data | filter_data_type %}
312 | {% set datatype = datatype_list[0]%}
313 |
321 | {%- endblock data_widget_view -%}
322 |
323 | {%- block footer %}
324 | {% set mimetype = 'application/vnd.jupyter.widget-state+json'%}
325 | {% if mimetype in nb.metadata.get("widgets",{})%}
326 |
329 | {% endif %}
330 | {{ super() }}
331 | {%- endblock footer-%}
332 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2025 FutureHouse
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/src/fhda/prompts.py:
--------------------------------------------------------------------------------
1 | # System prompt for bioinformatics tasks
2 | CAPSULE_SYSTEM_PROMPT_HYPOTHESIS = """
3 | You are an expert bioinformatician and seasoned biological data scientist tasked with
4 | creating a Jupyter notebook to analyze data relating to a hypothesis. Your goal is to
5 | validate whether the data provided supports the hypothesis or not.
6 | """
7 |
8 | CAPSULE_SYSTEM_PROMPT_MCQ = """
9 | You are an expert bioinformatician and seasoned biological data scientist.
10 | Your task is to create a comprehensive Jupyter notebook named 'notebook.ipynb' that analyzes data to answer a Multiple Choice Question (MCQ).
11 | The notebook should contain all necessary artifacts (plots, tables, print outputs) to fully answer this question, structured in a way that another model could use to derive the answer.
12 | """
13 |
14 | CAPSULE_SYSTEM_PROMPT_OPEN = """
15 | You are an expert bioinformatician and seasoned biological data scientist.
16 | Your task is to create a comprehensive Jupyter notebook named 'notebook.ipynb' that analyzes data to answer an open-ended question.
17 | The notebook should contain all necessary artifacts (plots, tables, print outputs) to fully answer this question, structured in a way that another model could use to derive the answer.
18 | """
19 |
20 | CAPSULE_SYSTEM_PROMPT_QUERY = """
21 | You are an expert bioinformatician and seasoned biological data scientist.
22 | Your task is to create a comprehensive Jupyter notebook named 'notebook.ipynb' that analyzes data to answer a user query.
23 | The notebook should contain all necessary artifacts (plots, tables, print outputs) to fully answer this question.
24 | Take your time to think through the question and the data before writing any code, explore the data rigorously and defend your conclusions rigorously.
25 | """
26 |
27 | # Guidelines for R code output optimization
28 | R_SPECIFIC_GUIDELINES = """Guidelines for using the R programming language:
29 | 1. Load packages using this format to minimize verbose output:
30 | ```r
31 | if (!requireNamespace("package_name", quietly = TRUE)) {{
32 | install.packages("package_name")
33 | }}
34 | suppressPackageStartupMessages(library(package_name))
35 | ```
36 | 2. You must use the tidyverse wherever possible: dplyr, tidyr, ggplot2, readr, stringr, forcats, purrr, tibble, and lubridate.
37 |
38 | 3. All plots must be made using ggplot2. Here is an example of how to make a plot:
39 |
40 | # Create a density scatter plot of FSC-A vs SSC-A
41 | plot_data <- as.data.frame(dmso_data[, c("FSC-A", "SSC-A")])
42 | scatter_plot <- ggplot2::ggplot(plot_data, ggplot2::aes(x = `FSC-A`, y = `SSC-A`)) +
43 | ggplot2::geom_hex(bins = 100) +
44 | ggplot2::scale_fill_viridis_c(trans = "log10") +
45 | ggplot2::labs(
46 | title = "FSC-A vs SSC-A Density Plot (DMSO Control)",
47 | x = "FSC-A",
48 | y = "SSC-A"
49 | ) +
50 | ggplot2::theme_minimal()
51 |
52 | 3. Use explicit namespace qualification for functions. For example, use dplyr::select() instead of select().
53 |
54 | 4. For data operations, suppress messages about column name repairs:
55 | ```r
56 | variable_name <- read_excel("
.csv", col_names = FALSE, .name_repair = "minimal")
57 | ```
58 | """
59 |
60 |
61 | # General notebook guidelines
62 | GENERAL_NOTEBOOK_GUIDELINES = """
63 | General Guidelines:
64 | - Write small to medium-sized cells for easier debugging.
65 | - Edit existing cells by their index number when fixing bugs, rather than creating new ones.
66 | - Check dataframe shapes before printing. Use head() for large dataframes.
67 | - Ensure each cell executes successfully before moving to the next.
68 | - Assume you already have the packages you need installed and only install new ones if you receive errors.
69 | - If you need to install packages, use pip or mamba.
70 | - All cells are by default {language} cells. Use {language} or bash tools for all analysis.
71 | - You can use bash cells by adding %%bash to the first line of the cell or running a subprocess.
72 | - You can only create code cells, no markdown cells.
73 | """
74 |
75 |
76 | AVOID_IMAGES = """
77 | AVOID USING PLOTS/IMAGES. USE TABLES AND PRINT OUTPUTS INSTEAD AS MUCH AS POSSIBLE.
78 | """
79 |
80 | BASH_TOOL_USAGE = """
81 | If you need to use Busco, you can use it through udocker as follows:
82 |
83 | ```bash
84 | # BUSCO Guidelines:
85 | # 1. Set up the required directory structure for BUSCO:
86 | mkdir busco_downloads
87 | mkdir busco_downloads/lineages
88 | mv busco_downloads/lineages # Move your downloaded lineage database
89 |
90 | # 2. Run BUSCO analysis on protein files:
91 | for protein_file in *. ; do
92 | output_name=$(echo "$protein_file" | sed "s/.$/.busco/g")
93 | udocker --allow-root run -u $(id -u) \
94 | -v /content/:/busco_wd \
95 | ezlabgva/busco:v5.8.0_cv1 \
96 | busco -i $protein_file \
97 | -m prot \
98 | --offline \
99 | -o $output_name \
100 | -l
101 | done
102 |
103 | # Note: Replace the following placeholders:
104 | # - : Your downloaded BUSCO lineage database directory
105 | # - : Your protein file extension (e.g., faa, fasta)
106 | # - : Name of the BUSCO lineage to use (e.g., eukaryota_odb10)
107 | ```
108 |
109 | You can also use mafft, clipkit, fastqc, iqtree, metaeuk, perl, phykit through the command line.
110 | """
111 |
112 | # Agnostic to MCQ vs hypothesis
113 | CHAIN_OF_THOUGHT_AGNOSTIC = """
114 | Follow these steps to create your notebook, using chain-of-thought reasoning at each stage:
115 |
116 | 1. Load Data and Perform Descriptive Statistics:
117 |
118 | - Identify which data files are most relevant to resolving the task.
119 | - Plan how to load these files efficiently in {language}.
120 | - List the specific descriptive statistics you plan to use (e.g., summary(), str(), head()).
121 | - Consider potential issues like missing data or unexpected formats. How will you handle each?
122 | - Plan how to present this information clearly in the notebook.
123 | - Write down key statistics you expect to see and how you'll interpret them.
124 | - Consider potential data quality issues and how you'll address them.
125 |
126 | Execute your plan to load data and perform descriptive statistics.
127 |
128 | 2. Develop Analysis Plan:
129 |
130 | - Break down each task into testable components. List these components.
131 | - For each component, list appropriate statistical tests or visualizations.
132 | - Consider alternative approaches for each component and justify your choices.
133 | - Identify potential confounding factors and how to address them.
134 | - Plan the sequence of your analysis steps, explaining the rationale for each.
135 | - Consider how this analysis plan will be documented in the notebook.
136 | - List potential statistical assumptions for your chosen methods and how you'll test them.
137 | - Think about how your analysis plan addresses your original task.
138 |
139 | Write out your analysis plan as comments in the notebook.
140 |
141 | 3. Execute Analysis Plan:
142 |
143 | - For each step in your analysis plan, list the {language} or bash functions and libraries you'll use.
144 | - Think about how to structure your code for readability and efficiency.
145 | - Plan how to document your code with clear comments.
146 | - Consider how to present results clearly, using tables or visualizations where appropriate.
147 | - Ensure that all outputs are clearly labeled and explained in the context of the task.
148 | - Plan how you'll interpret each result in relation to the original task.
149 | - Consider potential unexpected results and how you'll handle them.
150 |
151 | Execute your analysis plan, creating new cells as needed.
152 |
153 | 4. Conclude and Submit Answer:
154 |
155 | - Reflect on how your results relate to the original task.
156 | - Consider any limitations or uncertainties in your analysis.
157 | - Plan a concise summary of your findings.
158 | - Think about how to phrase your conclusion as clear statements.
159 | - Ensure that the notebook contains all necessary information for another model to derive these answers.
160 | - Consider any additional insights or patterns you've noticed during the analysis.
161 | - Think about potential follow-up questions or areas for further investigation.
162 |
163 | """
164 |
165 | SUBMIT_ANSWER_HYPOTHESIS = """
166 | [Use the submit_answer tool to submit your final answer as a single string either "True" or "False"]
167 | Remember, the final notebook should contain all necessary artifacts (plots, tables, print outputs) to solve the task provided.
168 | """
169 | SUBMIT_ANSWER_SINGLE = """
170 | [Use the submit_answer tool to submit your final answer as a single string]
171 | IMPORTANT: Wrap your answer in XML tags
172 | Example output:
173 | ```
174 | submit_answer("CD94") or submit_answer("-1.23")
175 | ```
176 | Remember, the final notebook should contain all necessary artifacts (plots, tables, print outputs) to solve the task provided.
177 | """
178 | SUBMIT_ANSWER_OPEN = """
179 | [Use the submit_answer tool to submit your final answer as a single string with your short answer]
180 | IMPORTANT: Wrap your answer in XML tags
181 | Example output:
182 | ```
183 | submit_answer("Your concise answer to the question")
184 | ```
185 | Remember, the final notebook should contain all necessary artifacts (plots, tables, print outputs) to solve the task provided.
186 | """
187 | SUBMIT_ANSWER_MCQ = """
188 | [Use the submit_answer tool to submit your final answer as a single string with the letter choice]
189 | IMPORTANT: Wrap your answer in XML tags
190 | Example output:
191 | ```
192 | submit_answer("A") or submit_answer("B") or submit_answer("C") or submit_answer("D")
193 | ```
194 | Remember, the final notebook should contain all necessary artifacts (plots, tables, print outputs) to solve the task provided.
195 | """
196 |
197 | HYPOTHESIS_PROMPT_TEMPLATE = f"""
198 |
199 | Here is the hypothesis you need to address:
200 |
201 |
202 | {{hypothesis}}
203 |
204 |
205 | {CHAIN_OF_THOUGHT_AGNOSTIC}
206 | {SUBMIT_ANSWER_HYPOTHESIS}
207 | {GENERAL_NOTEBOOK_GUIDELINES}
208 | {R_SPECIFIC_GUIDELINES}
209 | """
210 | # MCQ
211 | MCQ_PROMPT_TEMPLATE = f"""
212 | Here is the question you need to address:
213 |
214 | {{question}}
215 |
216 |
217 | {CHAIN_OF_THOUGHT_AGNOSTIC}
218 | {SUBMIT_ANSWER_MCQ}
219 | {GENERAL_NOTEBOOK_GUIDELINES}
220 | {R_SPECIFIC_GUIDELINES}
221 | """
222 | # Open answer
223 | OPEN_PROMPT_TEMPLATE = f"""
224 | Here is the question you need to address:
225 |
226 |
227 | {{question}}
228 |
229 |
230 | {CHAIN_OF_THOUGHT_AGNOSTIC}
231 | {SUBMIT_ANSWER_OPEN}
232 | {GENERAL_NOTEBOOK_GUIDELINES}
233 | {R_SPECIFIC_GUIDELINES}
234 | """
235 |
236 | CONTINUATION_PROMPT_TEMPLATE = f"""
237 | {GENERAL_NOTEBOOK_GUIDELINES}
238 |
239 | You have been provided with a notebook previously generated by an agent based on a user's research question.
240 |
241 | This was the user's research question:
242 |
243 | {{previous_research_question}}
244 |
245 |
246 | This was the final answer generated by the previous agent:
247 |
248 | {{previous_final_answer}}
249 |
250 |
251 | The user has now tasked you with addressing a new query:
252 |
253 | {{query}}
254 |
255 |
256 | Please make any edits required to the notebook and the answer to address the new query. Be extremely diligent and ensure that the notebook is fully updated to address the new query.
257 | Note you may have to run all cells one by one again if the user query involved updating one of the intermediate cells and subsequent cells depend on it.
258 | Once you have updated the notebook, use the submit_answer tool to submit your final answer once the user's query is addressed.
259 | """
260 |
--------------------------------------------------------------------------------
/src/fhda/tortoise.py:
--------------------------------------------------------------------------------
1 | import os
2 | import uuid
3 | import asyncio
4 | import copy
5 | from typing import Any, Callable, Optional
6 | from os import PathLike
7 | import time
8 | import json
9 | from pydantic import BaseModel, Field
10 | from tenacity import (
11 | retry,
12 | stop_after_attempt,
13 | wait_exponential,
14 | retry_if_exception_type,
15 | )
16 | from . import config as cfg
17 |
18 | from futurehouse_client import FutureHouseClient
19 | from futurehouse_client.models import TaskRequest, RuntimeConfig
20 | from futurehouse_client.models.app import AuthType, Stage
21 | import anthropic
22 | import logging
23 | import traceback
24 |
25 | logger = logging.getLogger(__name__)
26 | logger.setLevel(logging.INFO)
27 |
28 |
29 | class Step(BaseModel):
30 | """A step in the agent execution pipeline."""
31 |
32 | name: str = Field(
33 | description="Name of the job to run (e.g. 'job-futurehouse-data-analysis-crow-high')"
34 | )
35 | llm_call: bool = Field(
36 | default=False, description="Whether to call the LLM for the step"
37 | )
38 | include_search_tool: bool = Field(
39 | default=False, description="Whether to include the search tool in the LLM call"
40 | )
41 | model_name: str = Field(
42 | default=cfg.DEFAULT_MODEL, description="Name of the model to use for the step"
43 | )
44 | prompt_template: str = Field(description="Prompt template to use for the step")
45 | prompt_args: dict[str, Any] = Field(
46 | default_factory=dict,
47 | description="Keyword arguments to format the prompt template.",
48 | )
49 | input_files: dict[str, str] = Field(
50 | default_factory=dict, description="Files to upload {'source_path': 'dest_name'}"
51 | )
52 | output_files: dict[str, str] = Field(
53 | default_factory=dict,
54 | description="Files to download {'source_name': 'dest_path'}",
55 | )
56 | step_id: str = Field(
57 | default_factory=lambda: str(uuid.uuid4()),
58 | description="Small UID for the step",
59 | )
60 | n_replicate_tasks: int = Field(
61 | default=1, description="Number of parallel tasks to run"
62 | )
63 | runtime_config: RuntimeConfig = Field(
64 | default_factory=RuntimeConfig, description="Configuration for the step"
65 | )
66 | post_process: Optional[Callable[[dict[str, Any], str], None]] = Field(
67 | default=None, description="Function to run after step completion"
68 | )
69 | prompt_generator: Optional[Callable[[], list[tuple[str, dict[str, Any]]]]] = Field(
70 | default=None,
71 | description="Function to generate prompts and args for parallel tasks based on previous results",
72 | )
73 | timeout: int = Field(default=15 * 60, description="Timeout for the step in seconds")
74 |
75 | def format_prompt(self) -> str:
76 | """Format the prompt template with the provided arguments."""
77 | final_prompt = self.prompt_template.format(**self.prompt_args)
78 | return final_prompt
79 |
80 |
81 | class Tortoise:
82 | """Runner for multi-step agent pipelines."""
83 |
84 | def __init__(self, api_key: str, environment: str = "PROD"):
85 | """Initialize the tortoise framework with FutureHouse API key."""
86 | self.client = FutureHouseClient(
87 | auth_type=AuthType.API_KEY,
88 | api_key=api_key,
89 | verbose_logging=True,
90 | stage=getattr(Stage, environment.upper(), Stage.PROD),
91 | )
92 | self.steps: list[Step] = []
93 | self.results: dict[str, Any] = {}
94 |
95 | def add_step(self, step: Step) -> None:
96 | """Add a step to the pipeline."""
97 | self.steps.append(step)
98 |
99 | def save_results(self, output_dir: str | PathLike = "output") -> None:
100 | """Save the results to a JSON file."""
101 | results_path = f"{output_dir}/results_{time.strftime('%Y%m%d_%H%M%S')}.json"
102 | logger.info(f"Saving all results to {results_path}")
103 | try:
104 | os.makedirs(output_dir, exist_ok=True)
105 | serializable_results = {}
106 | for step_id, step_result in self.results.items():
107 | serializable_results[step_id] = dict(step_result)
108 |
109 | with open(results_path, "w") as f:
110 | json.dump(serializable_results, f, indent=2, default=str)
111 | logger.info(f"Results successfully saved to {results_path}")
112 | except Exception as e:
113 | logger.error(f"Error saving results to {results_path}: {e}")
114 |
115 | @retry(
116 | stop=stop_after_attempt(3),
117 | wait=wait_exponential(multiplier=1, min=2, max=10),
118 | retry=retry_if_exception_type(Exception),
119 | )
120 | def _upload_file_with_retry(
121 | self, job_name: str, file_path: str, upload_id: str
122 | ) -> None:
123 | """Upload a file with retry logic."""
124 | self.client.upload_file(job_name, file_path=file_path, upload_id=upload_id)
125 |
126 | @retry(
127 | stop=stop_after_attempt(3),
128 | wait=wait_exponential(multiplier=1, min=2, max=10),
129 | retry=retry_if_exception_type(Exception),
130 | )
131 | def _download_file_with_retry(
132 | self, job_name: str, trajectory_id: str, file_path: str, destination_path: str
133 | ) -> None:
134 | """Download a file with retry logic."""
135 | self.client.download_file(
136 | job_name,
137 | trajectory_id=trajectory_id,
138 | file_path=file_path,
139 | destination_path=destination_path,
140 | )
141 |
142 | def _create_task_requests(
143 | self, step: Step, runtime_config: RuntimeConfig
144 | ) -> list[TaskRequest]:
145 | """Create task requests with either identical or dynamic prompts.
146 |
147 | Args:
148 | step: The step configuration
149 | runtime_config: The runtime configuration for the task
150 |
151 | Returns:
152 | List of task requests to be executed
153 | """
154 | task_requests = []
155 | task_count = max(step.n_replicate_tasks, 1)
156 |
157 | if step.model_name:
158 | agent_config = cfg.get_custom_agent_config(step.model_name)
159 | runtime_config.agent = agent_config
160 |
161 | if step.runtime_config.continued_job_id:
162 | task_ids = self.results[str(step.runtime_config.continued_job_id)][
163 | "task_ids"
164 | ]
165 | if len(task_ids) > 1:
166 | logger.warning(
167 | f"Continued job {step.runtime_config.continued_job_id} has multiple task ids, using the first one"
168 | )
169 | runtime_config.continued_job_id = str(task_ids[0])
170 |
171 | if step.prompt_generator and task_count > 1:
172 | # Generate dynamic prompts based on previous results
173 | prompt_pairs = step.prompt_generator()
174 | # Create a task request for each generated prompt
175 | for prompt_text, prompt_args in prompt_pairs[
176 | :task_count
177 | ]: # Limit to requested parallel count
178 | step_copy = copy.deepcopy(step)
179 | step_copy.prompt_template = prompt_text
180 | step_copy.prompt_args = prompt_args
181 | query = step_copy.format_prompt()
182 | task_requests.append(
183 | TaskRequest(
184 | name=step.name,
185 | query=query,
186 | runtime_config=runtime_config,
187 | )
188 | )
189 | else:
190 | # Default behavior: use the same prompt for all tasks
191 | query = step.format_prompt()
192 | task_requests = [
193 | TaskRequest(
194 | name=step.name,
195 | query=query,
196 | runtime_config=runtime_config,
197 | )
198 | ] * task_count
199 |
200 | return task_requests
201 |
202 | async def call_llm(self, step: Step) -> list:
203 | """Call the LLM for the step."""
204 | anthropic_client = anthropic.Anthropic()
205 | # TODO: This is a hack to get the model name without the provider prefix
206 | model_name = step.model_name.replace("anthropic/", "")
207 | if step.include_search_tool:
208 | tools = [
209 | {
210 | "type": "web_search_20250305",
211 | "name": "web_search",
212 | }
213 | ]
214 | else:
215 | tools = []
216 | response = anthropic_client.messages.create(
217 | model=model_name,
218 | messages=[
219 | {
220 | "role": "user",
221 | "content": step.prompt_template,
222 | }
223 | ],
224 | tools=tools,
225 | max_tokens=8192,
226 | )
227 | result = "\n".join([r.text for r in response.content if hasattr(r, "text")])
228 | return [result]
229 |
230 | async def _run_tasks_with_retry(
231 | self, task_requests, progress_bar, verbose, timeout
232 | ):
233 | """Run tasks with retry logic."""
234 | return await self.client.arun_tasks_until_done(
235 | task_requests,
236 | progress_bar=progress_bar,
237 | verbose=verbose,
238 | timeout=timeout,
239 | concurrency=1, # Reduce concurrency to avoid overwhelming the server
240 | )
241 |
242 | async def run_pipeline(
243 | self, output_dir: str | PathLike = "output"
244 | ) -> dict[str, Any]:
245 | """Run the entire pipeline of steps."""
246 | os.makedirs(output_dir, exist_ok=True)
247 |
248 | for i, step in enumerate(self.steps):
249 | logger.info(f"Running step {i + 1}/{len(self.steps)}: {step.name}")
250 | if not step.runtime_config.upload_id:
251 | step.runtime_config.upload_id = step.step_id
252 |
253 | for source_path, dest_name in step.input_files.items():
254 | logger.info(f"Uploading file {source_path} as {dest_name}")
255 | try:
256 | self._upload_file_with_retry(
257 | step.name,
258 | file_path=source_path,
259 | upload_id=step.runtime_config.upload_id,
260 | )
261 | except Exception as e:
262 | logger.error(
263 | f"Failed to upload file {source_path} after multiple retries: {e}"
264 | )
265 | raise
266 |
267 | if step.llm_call:
268 | task_responses = await self.call_llm(step)
269 | task_ids = [f"llm_{str(uuid.uuid4())[:8]}"]
270 | success_rate = 1
271 | else:
272 | task_requests = self._create_task_requests(step, step.runtime_config)
273 |
274 | logger.info(
275 | f"Running {len(task_requests)} task{'s' if len(task_requests) > 1 else ''}"
276 | )
277 | try:
278 | task_responses = await self._run_tasks_with_retry(
279 | task_requests,
280 | progress_bar=True,
281 | verbose=False,
282 | timeout=step.timeout,
283 | )
284 | except Exception as e:
285 | logger.error(
286 | f"Failed to run tasks for step {step.step_id} after multiple retries: {e}"
287 | )
288 | logger.error(f"Full traceback:\n{traceback.format_exc()}")
289 | # Create an error result entry and continue to the next step
290 | self.results[step.step_id] = {
291 | "task_ids": [],
292 | "task_responses": [],
293 | "success_rate": 0,
294 | "error": str(e),
295 | }
296 | continue
297 |
298 | task_ids = [str(task.task_id) for task in task_responses]
299 | success_rate = sum(
300 | [task.status == "success" for task in task_responses]
301 | ) / len(task_responses)
302 | logger.info(f"Task success rate: {success_rate * 100}%")
303 |
304 | self.results[step.step_id] = {
305 | "task_ids": task_ids,
306 | "task_responses": task_responses,
307 | "success_rate": success_rate,
308 | }
309 |
310 | os.makedirs(f"{output_dir}/{step.step_id}", exist_ok=True)
311 |
312 | for idx, task_id in enumerate(task_ids):
313 | for source_name, dest_path in step.output_files.items():
314 | try:
315 | # Add index suffix only when there are multiple tasks
316 | path_suffix = f"_{idx}" if len(task_ids) > 1 else ""
317 | if "." in dest_path:
318 | base, ext = os.path.splitext(dest_path)
319 | dest_path_with_idx = f"{base}{path_suffix}{ext}"
320 | else:
321 | dest_path_with_idx = f"{dest_path}{path_suffix}"
322 |
323 | path = f"{output_dir}/{step.step_id}/{dest_path_with_idx}"
324 | os.makedirs(
325 | os.path.dirname(os.path.abspath(path)), exist_ok=True
326 | )
327 | logger.info(f"Downloading file {source_name} to {path}")
328 | try:
329 | self._download_file_with_retry(
330 | step.name,
331 | trajectory_id=task_id,
332 | file_path=source_name,
333 | destination_path=path,
334 | )
335 | except Exception as e:
336 | logger.error(
337 | f"Failed to download {source_name} from task {task_id} after multiple retries: {e}"
338 | )
339 | except Exception as e:
340 | logger.error(
341 | f"Error downloading {source_name} from task {task_id}: {e}"
342 | )
343 |
344 | if step.post_process:
345 | logger.info(f"Running post-processing for step {step.step_id}")
346 | step.post_process(
347 | self.results[step.step_id], f"{output_dir}/{step.step_id}"
348 | )
349 |
350 | logger.info(f"Completed step {i + 1}/{len(self.steps)}")
351 |
352 | self.save_results(output_dir)
353 | return self.results
354 |
355 | def run(self, output_dir: str | PathLike = "output") -> dict[str, Any]:
356 | """Synchronous version of run_pipeline."""
357 | return asyncio.run(self.run_pipeline(output_dir))
358 |
--------------------------------------------------------------------------------
/src/fhda/storage.py:
--------------------------------------------------------------------------------
1 | """Module containing storage utilities for Google Cloud Platform (GCP) and Google Cloud Storage (GCS)."""
2 |
3 | import asyncio
4 | import base64
5 | import concurrent.futures
6 | import logging
7 | import os
8 | import re
9 | import shutil
10 | from typing import Self
11 |
12 | import aiofiles
13 | import google.api_core.exceptions
14 | import google.auth
15 | import httpx
16 | from google.cloud import secretmanager
17 | from google.cloud.storage import Client
18 | from google_crc32c import Checksum
19 | from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
20 | from requests.adapters import HTTPAdapter
21 | from tqdm import tqdm
22 |
23 | logger = logging.getLogger(__name__)
24 |
25 | DEFAULT_BUCKET = "aviary-storage"
26 | DEFAULT_KEY = os.path.expanduser("~/.keys/aviary-storage-service.json")
27 | DEFAULT_STORAGE_PATH = os.path.expanduser("~/aviary_data/")
28 | DEFAULT_GCP_PROJECT_ID = "362315315966" # Corresponds to "paperqa" project
29 | MAX_THREADS = 100
30 |
31 |
32 | def validate_google_app_creds() -> None:
33 | """Validate we have a google application credential set.
34 |
35 | Priority order:
36 | 1. GOOGLE_APPLICATION_CREDENTIALS environment variable
37 | 2. Default key path
38 | 3. Fetch key from Secret Manager (and cache in default key path)
39 | """
40 | if "GOOGLE_APPLICATION_CREDENTIALS" in os.environ:
41 | # This code path is mostly meant for CI, which uses a GitHub secret,
42 | # not a key file.
43 | return
44 |
45 | if os.path.exists(DEFAULT_KEY):
46 | return
47 |
48 | logger.info("aviary-storage-service account key not found, attempting to fetch...")
49 | client = secretmanager.SecretManagerServiceClient()
50 | try:
51 | response = client.access_secret_version(
52 | request={
53 | "name": f"projects/{DEFAULT_GCP_PROJECT_ID}/secrets/AVIARY-STORAGE-SERVICE-KEY/versions/latest"
54 | }
55 | )
56 | except google.api_core.exceptions.RetryError as e:
57 | # Could use better error handling here, but it's a little confusing how they chain exceptions
58 | raise RuntimeError(
59 | "Failed to fetch 'aviary-storage-service' key from Secret Manager. "
60 | "Confirm that you are authenticated by running `gcloud auth application-default login`"
61 | ) from e
62 |
63 | payload = response.payload.data.decode("UTF-8")
64 | os.makedirs(os.path.dirname(DEFAULT_KEY), exist_ok=True)
65 | with open(DEFAULT_KEY, "w") as f: # noqa: FURB103
66 | f.write(payload)
67 | logger.info(
68 | f"Successfully stored aviary-storage-service account key in {DEFAULT_KEY}."
69 | )
70 |
71 |
72 | def auth_required(func):
73 | """Decorator to ensure that the user is authenticated with GCP before calling."""
74 |
75 | def wrapper(*args, **kwargs):
76 | validate_google_app_creds()
77 | os.environ.setdefault("GOOGLE_APPLICATION_CREDENTIALS", DEFAULT_KEY)
78 | google.auth.default() # Check authentication
79 | return func(*args, **kwargs)
80 |
81 | return wrapper
82 |
83 |
84 | class DataRepo(BaseModel):
85 | model_config = ConfigDict(extra="forbid")
86 |
87 | name: str = Field(
88 | description=(
89 | "Subpath to the target directory within the cloud bucket `bucket`,"
90 | " something like 'relative/path/to/sub/bucket'. Set to empty string to use"
91 | " the root of the bucket."
92 | ),
93 | )
94 |
95 | local_path: str = Field(
96 | default="UNSET",
97 | description=(
98 | "Set to the target directory to mirror files. If left as the default of"
99 | " 'UNSET', it will be set to be /."
100 | ),
101 | )
102 | bucket: str = Field(
103 | default=DEFAULT_BUCKET,
104 | description=(
105 | "Cloud bucket name like 'aviary-storage'. An analogy with a local"
106 | " filesystem is the drive (e.g. 'C:' on Windows)."
107 | ),
108 | )
109 |
110 | validate_gcs_auth: bool = Field(
111 | default=True,
112 | description=(
113 | "Set True (default) to validate GCS authentication at construction time."
114 | ),
115 | )
116 |
117 | def __bool__(self) -> bool:
118 | """Determines truthiness based on whether the name and local_path are set."""
119 | return bool(self.name and self.local_path and self.local_path != "UNSET")
120 |
121 | @staticmethod
122 | def get_local_storage_path() -> str:
123 | return os.getenv("AVIARY_LOCAL_STORAGE", DEFAULT_STORAGE_PATH)
124 |
125 | @field_validator("name")
126 | @classmethod
127 | def _remove_slash(cls, value: str) -> str:
128 | return value.rstrip("/")
129 |
130 | @property
131 | def gcs_name(self) -> str:
132 | return f"{self.name}/"
133 |
134 | @model_validator(mode="after")
135 | def set_local_path(self) -> Self:
136 | if self.local_path == "UNSET":
137 | self.local_path = os.path.join(self.get_local_storage_path(), self.name)
138 | return self
139 |
140 | def mkdir(self, remove_existing: bool = False):
141 | if remove_existing:
142 | shutil.rmtree(self.local_path, ignore_errors=True)
143 | os.makedirs(self.local_path, exist_ok=True)
144 |
145 | @auth_required
146 | def push(
147 | self,
148 | overwrite: bool = False,
149 | include: re.Pattern | str | None = None,
150 | exclude: re.Pattern | str | None = None,
151 | progress: bool = False,
152 | ) -> None:
153 | logger.info(f"Pushing data repo: {self.name}")
154 | bucket = _get_gcs_client().get_bucket(self.bucket)
155 |
156 | include = _resolve_pattern(include)
157 | exclude = _resolve_pattern(exclude)
158 |
159 | # If overwrite is True, delete the contents of the bucket directory
160 | if overwrite:
161 | blobs = bucket.list_blobs(prefix=self.gcs_name)
162 | executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS)
163 | for blob in blobs:
164 | executor.submit(lambda b: b.delete(), blob)
165 | executor.shutdown(wait=True)
166 |
167 | def upload(local_path: str, blob_path: str):
168 | blob = bucket.blob(blob_path)
169 |
170 | # Check if the blob already exists and has the same hash
171 | if blob.exists():
172 | blob.reload() # Ensure that the blob's metadata is up-to-date
173 | if blob.crc32c == compute_crc32c(local_path):
174 | pbar.update()
175 | return
176 |
177 | # Upload the file
178 | logger.debug(f"Pushing {local_path} to gcs://{blob_path}")
179 | blob.upload_from_filename(local_path)
180 | blob.patch() # Save metadata changes to GCS
181 | pbar.update()
182 |
183 | executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS)
184 | pbar = tqdm(
185 | disable=not progress, desc=f"Push [{self.name}]", unit="files", ncols=0
186 | )
187 |
188 | # Walk through the local directory and upload each file
189 | count = 0
190 | for root, _, files in os.walk(self.local_path):
191 | for file in files:
192 | if file.endswith(".checksum"):
193 | continue
194 |
195 | local_path = os.path.join(root, file)
196 | blob_path = os.path.join(
197 | self.name, os.path.relpath(local_path, self.local_path)
198 | )
199 |
200 | if not _passes_filters(include, exclude, local_path):
201 | continue
202 |
203 | executor.submit(upload, local_path, blob_path)
204 | count += 1
205 |
206 | pbar.total = count
207 | executor.shutdown(wait=True)
208 | pbar.close()
209 |
210 | @auth_required
211 | def pull(
212 | self,
213 | overwrite: bool = False,
214 | include: re.Pattern | str | None = None,
215 | exclude: re.Pattern | str | None = None,
216 | progress: bool = False,
217 | ):
218 | logger.info(f"Pulling data repo: {self.name}")
219 | bucket = _get_gcs_client().get_bucket(self.bucket)
220 |
221 | include = _resolve_pattern(include)
222 | exclude = _resolve_pattern(exclude)
223 |
224 | # If overwrite is True, delete the contents of the local directory
225 | if overwrite:
226 | shutil.rmtree(self.local_path)
227 | self.mkdir()
228 |
229 | def download(blob, local_path: str):
230 | blob.reload()
231 | if os.path.exists(local_path) and blob.crc32c == compute_crc32c(local_path):
232 | # print(f"Skipping {local_path}; no changes detected.")
233 | pbar.update()
234 | return
235 |
236 | local_dir_path = os.path.dirname(local_path)
237 | if not os.path.exists(local_dir_path):
238 | os.makedirs(local_dir_path)
239 |
240 | logger.debug(f"Pulling gcs://{blob.name} to {local_path}")
241 | blob.download_to_filename(local_path)
242 | with open(f"{local_path}.checksum", "w") as f: # noqa: FURB103
243 | f.write(blob.crc32c)
244 | pbar.update()
245 |
246 | executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS)
247 | pbar = tqdm(
248 | disable=not progress, desc=f"Pull [{self.name}]", unit=" files", ncols=0
249 | )
250 |
251 | # Walk through the bucket directory and download each file
252 | blobs = bucket.list_blobs(prefix=self.gcs_name)
253 | count = 0
254 | n_name = len(self.gcs_name)
255 | for blob in blobs:
256 | local_path = os.path.join(self.local_path, blob.name[n_name:])
257 | if local_path.endswith(".checksum"):
258 | # ???
259 | continue
260 |
261 | if not _passes_filters(include, exclude, local_path):
262 | continue
263 |
264 | executor.submit(download, blob, local_path)
265 | count += 1
266 |
267 | pbar.total = count
268 | executor.shutdown(wait=True)
269 | pbar.close()
270 |
271 | @auth_required
272 | def remote_exists(self) -> bool:
273 | bucket = Client().get_bucket(self.bucket)
274 | return any(True for _ in bucket.list_blobs(prefix=self.gcs_name))
275 |
276 | @model_validator(mode="after")
277 | def check_auth(self) -> Self:
278 | if self.validate_gcs_auth:
279 | self.remote_exists() # Validate we can connect to GCS
280 | return self
281 |
282 | def local_exists(self) -> bool:
283 | return os.path.exists(self.local_path)
284 |
285 |
286 | def compute_crc32c(path: str):
287 | checksum_path = f"{path}.checksum"
288 | if os.path.exists(checksum_path) and os.path.getmtime(
289 | checksum_path
290 | ) > os.path.getmtime(path):
291 | with open(checksum_path) as f: # noqa: FURB101
292 | return f.read()
293 | else:
294 | if os.path.getsize(path) > 500 * 1024 * 1024:
295 | logger.info(f"Computing checksum of {path}...")
296 | with open(path, "rb") as f: # noqa: FURB101
297 | data = f.read()
298 | crc32c = Checksum()
299 | crc32c.update(data)
300 | checksum = base64.b64encode(crc32c.digest()).decode("utf-8")
301 | with open(checksum_path, "w") as f: # noqa: FURB103
302 | f.write(checksum)
303 | return checksum
304 |
305 |
306 | def _resolve_pattern(pat: str | re.Pattern | None) -> re.Pattern | None:
307 | if isinstance(pat, str):
308 | try:
309 | pat = re.compile(pat)
310 | except re.error as e:
311 | raise ValueError(f'Invalid regex pattern "{pat}"') from e
312 | return pat
313 |
314 |
315 | def _passes_filters(
316 | include: re.Pattern | None, exclude: re.Pattern | None, string: str
317 | ) -> bool:
318 | if include is not None and not include.match(string):
319 | return False
320 | return not (exclude is not None and exclude.match(string))
321 |
322 |
323 | def _get_gcs_client() -> Client:
324 | # patch in a HTTPAdapter with a larger pool size
325 | # from https://stackoverflow.com/a/77740153
326 | client = Client()
327 | adapter = HTTPAdapter(pool_connections=MAX_THREADS, pool_maxsize=MAX_THREADS)
328 | client._http.mount("https://", adapter)
329 | client._http._auth_request.session.mount("https://", adapter)
330 | return client
331 |
332 |
333 | async def download_file(
334 | client: httpx.AsyncClient,
335 | download_url: str,
336 | local_path: str | os.PathLike,
337 | file_name: str,
338 | headers: dict[str, str],
339 | timeout: float | None,
340 | ) -> None:
341 | """Download a single file.
342 |
343 | Args:
344 | client: httpx.AsyncClient
345 | download_url: URL to download.
346 | local_path: Local path to download file.
347 | file_name: Name of file to download.
348 | headers: Dictionary of headers.
349 | timeout: Timeout.
350 |
351 | """
352 | response = await client.get(download_url, headers=headers, timeout=timeout)
353 | response.raise_for_status()
354 |
355 | file_path = os.path.join(local_path, file_name)
356 | async with aiofiles.open(file_path, "wb") as f:
357 | await f.write(response.content)
358 | print(f"Downloaded {file_path}")
359 |
360 |
361 | async def download_github_subdirectory(
362 | client: httpx.AsyncClient,
363 | repo_owner: str,
364 | repo_name: str,
365 | branch: str,
366 | subdirectory: str,
367 | local_path: str | os.PathLike,
368 | timeout: float | None,
369 | ) -> None:
370 | """Download a specific subdirectory from a GitHub repository.
371 |
372 | Args:
373 | client: httpx.AsyncClient
374 | repo_owner: GitHub repository owner.
375 | repo_name: GitHub repository name.
376 | branch: GitHub branch.
377 | subdirectory: Subdirectory to download.
378 | local_path: Local path to download to.
379 | timeout: Timeout.
380 | """
381 | # Headers with the API version and authentication (optional)
382 | headers = {
383 | "Accept": "application/vnd.github.v3+json",
384 | "Authorization": "token " + os.environ["GITHUB_TOKEN"],
385 | }
386 | api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/contents/{subdirectory}?ref={branch}"
387 | response = await client.get(api_url, headers=headers, timeout=timeout)
388 | response.raise_for_status() # Check for HTTP errors
389 | items = response.json()
390 |
391 | if not os.path.exists(local_path):
392 | os.makedirs(local_path)
393 |
394 | coroutines = []
395 | for item in items:
396 | if item["type"] == "file":
397 | coroutines.append(
398 | download_file(
399 | client,
400 | item["download_url"],
401 | local_path,
402 | item["name"],
403 | headers,
404 | timeout,
405 | )
406 | )
407 | elif item["type"] == "dir":
408 | new_subdir = os.path.join(subdirectory, item["name"])
409 | new_local_path = os.path.join(local_path, item["name"])
410 | coroutines.append(
411 | download_github_subdirectory(
412 | client,
413 | repo_owner,
414 | repo_name,
415 | branch,
416 | new_subdir,
417 | new_local_path,
418 | timeout,
419 | )
420 | )
421 |
422 | await asyncio.gather(*coroutines)
423 |
--------------------------------------------------------------------------------
/tutorial/consensus.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Multi-agent consensus tutorial\n",
8 | "\n",
9 | "In this tutorial, we will be using two different agents, Finch and Crow to do differential expression analysis on some RNASeq data from [here](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE52778). Additionally, we do consensus sampling with Finch to improve reliability of the results.\n",
10 | "\n",
11 | "The process follows four steps:\n",
12 | "1. Differential expression analysis: run 10 DEAs in parallel with Finch\n",
13 | "2. Consensus sampling: Aggregate the results of the DEAs with Finch\n",
14 | "3. Literature search: Use Crow to search the literature for the top differentially expressed genes\n",
15 | "4. Visualization: Use Finch to create a final interactive volcano plot containing all differentially expressed genes, their evidence and the evidence score.\n",
16 | "\n",
17 | "Let's get started!"
18 | ]
19 | },
20 | {
21 | "cell_type": "code",
22 | "execution_count": null,
23 | "metadata": {},
24 | "outputs": [],
25 | "source": [
26 | "import json\n",
27 | "import pandas as pd\n",
28 | "import uuid\n",
29 | "\n",
30 | "from futurehouse_client import FutureHouseClient, JobNames\n",
31 | "from futurehouse_client.models import TaskRequest, RuntimeConfig\n",
32 | "from futurehouse_client.models.app import AuthType\n",
33 | "import fhda.prompts as prompts"
34 | ]
35 | },
36 | {
37 | "cell_type": "code",
38 | "execution_count": null,
39 | "metadata": {},
40 | "outputs": [],
41 | "source": [
42 | "# Here are the prompts we'll be using\n",
43 | "TREATMENT = \"dexamethasone\"\n",
44 | "MECHANISM = \"airway smooth muscle cells\"\n",
45 | "CONTEXT = \"asthma\"\n",
46 | "N_TOP_GENES = 10\n",
47 | "DEA_PROMPT = \"\"\"\n",
48 | "Determine the effect of {treatment} on {mechanism} in {context}. \n",
49 | "\n",
50 | "Perform differential expression analysis and pathway analysis on relevant comparison groups. Map all gene IDs to gene symbols using annotation package such as ‘org.Hs.eg.db’.\n",
51 | "\n",
52 | "Generate volcano plots and heatmap of differentially expressed genes, and dot plots for enriched pathways, use gene symbols for labels where relevant.\n",
53 | "\n",
54 | "Output a single csv file named \"dea_results.csv\" with the results for all tested genes of the most relevant contrast, report both gene ID and gene symbol.\n",
55 | "\n",
56 | "If there is an error, keep trying, do not give up until you reach the end of the analysis. When mapping gene ID to gene symbol, consider all possible forms of gene IDs, keep trying until the gene symbols are obtained.\n",
57 | "\"\"\"\n",
58 | "\n",
59 | "CONSENSUS_PROMPT = f\"\"\"\n",
60 | "Combine these differential expression analysis results by calculating the mode of log2FC and adjusted p values. Output the results in a file named ‘consensus_results.csv’, include the columns gene_symbol, log2FC and adjusted P values. In a separate file named ‘top_genes.csv’, output the top {N_TOP_GENES} gene symbols of the consensus most significant genes with the column name “gene_symbol”. \n",
61 | "\n",
62 | "Create a stacked bar plot showing gene regulation consistency across all analyses. Plot regulation direction (up vs down) on x-axis and percentage of genes in each category on y-axis. Color-code by significance category: all analyses, >50% of analyses and <50% of analyses. Include percentages within each segment and a clear legend. Exclude genes that are non-significant across all analyses.\n",
63 | "\"\"\"\n",
64 | "\n",
65 | "PQA_PROMPT = \"\"\"\n",
66 | " What are the possible mechanisms for {gene} in the effect of {treatment} on {mechanism} in {context}?\n",
67 | " From 1 to 5, with 1 being no evidence of association at all and 5 being strong association with supporting evidence, how strong is the evidence supporting this mechanism?\n",
68 | " Give a concise summary for the evidence in up to 10 words, and a short summary of mechanisms in up to 20 words. Do not include references or links.\n",
69 | " Please share this information in json format in the form of: `\"gene_symbol\": , \"association_evidence_score\":[1...5], \"evidence_summary\": , \"mechanism_summary\": `.\n",
70 | " Share nothing else but the JSON output.\n",
71 | " \"\"\"\n",
72 | "\n",
73 | "VOLCANO_PROMPT = \"\"\"\n",
74 | "Make an interactive volcano plot. Colour-code by significance categories: top up-regulated genes, up-regulated genes, top down-regulated genes, down-regulated genes, and non-significant genes. Genes considered as top differentially expressed genes have extra annotation available in 'pqa_results.csv’.\n",
75 | "\n",
76 | "Include hover information according to the categories, for the top genes, on hover, show gene symbol, log2FC, adjusted p value, mechanism, evidence and evidence score. For up and down regulated genes that are not in top differentially expressed genes, show gene symbol, log2FC and adjusted p value. For non-significant genes, do not include hover information.\n",
77 | "\n",
78 | "For the annotations, remove all text in the brackets in the summary columns, and remove the fullstop at the end. For annotations with 6 words or more in a line, use text-wrap. Don’t include text on the plot itself. Include a legend explaining the color-codes.\n",
79 | "\n",
80 | "PLEASE USE TEXT WRAP FOR THE HOVER INFORMATION!\n",
81 | "\"\"\"\n",
82 | "\n",
83 | "\n",
84 | "def augment_query(query, language):\n",
85 | " guidelines = prompts.GENERAL_NOTEBOOK_GUIDELINES.format(language=language)\n",
86 | " if language == \"R\":\n",
87 | " guidelines = prompts.R_SPECIFIC_GUIDELINES.format(language=language)\n",
88 | " return (\n",
89 | " f\"{prompts.CHAIN_OF_THOUGHT_AGNOSTIC.format(language=language)}\\n\"\n",
90 | " f\"{guidelines}\"\n",
91 | " f\"Here is the research question to address:\\n\"\n",
92 | " f\"\\n\"\n",
93 | " f\"{query}\\n\"\n",
94 | " f\"\\n\"\n",
95 | " )"
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": null,
101 | "metadata": {},
102 | "outputs": [],
103 | "source": [
104 | "# Here we instantiate the FutureHouse client and define the job names\n",
105 | "FH_API_KEY = \"\" # Add your API key here\n",
106 | "# We will be creating three folders in GCS to store the results of the three steps\n",
107 | "DEA_UPLOAD_ID = f\"consensus_tutorial_dea_{str(uuid.uuid4())[:8]}\"\n",
108 | "CONSENSUS_UPLOAD_ID = f\"consensus_tutorial_consensus_{str(uuid.uuid4())[:8]}\"\n",
109 | "PQA_UPLOAD_ID = f\"consensus_tutorial_pqa_{str(uuid.uuid4())[:8]}\"\n",
110 | "INITIAL_RNASEQ_FILE = \"datasets/GSE52778_All_Sample_FPKM_Matrix.txt.gz\"\n",
111 | "client = FutureHouseClient(\n",
112 | " auth_type=AuthType.API_KEY,\n",
113 | " api_key=FH_API_KEY,\n",
114 | ")"
115 | ]
116 | },
117 | {
118 | "cell_type": "code",
119 | "execution_count": null,
120 | "metadata": {},
121 | "outputs": [],
122 | "source": [
123 | "# First let's upload the dataset to GCS and check the files were uploaded correctly\n",
124 | "client.upload_file(\n",
125 | " JobNames.FINCH, file_path=INITIAL_RNASEQ_FILE, upload_id=DEA_UPLOAD_ID\n",
126 | ")\n",
127 | "# Check what files were uploaded to your gcs folder\n",
128 | "client.list_files(JobNames.FINCH, upload_id=DEA_UPLOAD_ID)"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": null,
134 | "metadata": {},
135 | "outputs": [],
136 | "source": [
137 | "# Now let's run 5 Finch DEA tasks in parallel\n",
138 | "NUM_DEA_TASKS = 5\n",
139 | "TIMEOUT = 15 * 60\n",
140 | "runtime_config = RuntimeConfig(\n",
141 | " max_steps=30,\n",
142 | " upload_id=DEA_UPLOAD_ID,\n",
143 | " environment_config={\n",
144 | " \"default_cot_prompt\": False,\n",
145 | " \"language\": \"R\",\n",
146 | " },\n",
147 | ")\n",
148 | "task_request = TaskRequest(\n",
149 | " name=JobNames.FINCH,\n",
150 | " query=augment_query(\n",
151 | " DEA_PROMPT.format(treatment=TREATMENT, mechanism=MECHANISM, context=CONTEXT),\n",
152 | " \"R\",\n",
153 | " ),\n",
154 | " runtime_config=runtime_config,\n",
155 | ")\n",
156 | "dea_completed_tasks = await client.arun_tasks_until_done(\n",
157 | " [task_request for i in range(NUM_DEA_TASKS)], progress_bar=True, timeout=TIMEOUT\n",
158 | ")\n",
159 | "dea_task_ids = [str(task.task_id) for task in dea_completed_tasks]\n",
160 | "success = sum([task.status == \"success\" for task in dea_completed_tasks])\n",
161 | "print(f\"Task success rate: {success / NUM_DEA_TASKS * 100}%\")"
162 | ]
163 | },
164 | {
165 | "cell_type": "code",
166 | "execution_count": null,
167 | "metadata": {},
168 | "outputs": [],
169 | "source": [
170 | "# The Finch runs should take anywhere between 3-10 minutes to complete.\n",
171 | "# Once the runs have completed, lets's download the results upload them to a new folder in GCS and run a consensus step\n",
172 | "for c, task_id in enumerate(dea_task_ids):\n",
173 | " try:\n",
174 | " client.download_file(\n",
175 | " JobNames.FINCH,\n",
176 | " trajectory_id=task_id,\n",
177 | " file_path=\"dea_results.csv\",\n",
178 | " destination_path=f\"output/dea_results/dea_results_{c}.csv\",\n",
179 | " )\n",
180 | " except Exception as e:\n",
181 | " print(f\"Error downloading task results for task {task_id}: {e}\")\n",
182 | "\n",
183 | "# Now let's upload the whole directory of consensus results to GCS\n",
184 | "client.upload_file(\n",
185 | " JobNames.FINCH, file_path=\"output/dea_results\", upload_id=CONSENSUS_UPLOAD_ID\n",
186 | ")\n",
187 | "\n",
188 | "print(\"These files have been uploaded to GCS:\")\n",
189 | "print(client.list_files(JobNames.FINCH, upload_id=CONSENSUS_UPLOAD_ID))"
190 | ]
191 | },
192 | {
193 | "cell_type": "code",
194 | "execution_count": null,
195 | "metadata": {},
196 | "outputs": [],
197 | "source": [
198 | "# Now lets's run a single consensus step\n",
199 | "runtime_config = RuntimeConfig(\n",
200 | " max_steps=30,\n",
201 | " upload_id=CONSENSUS_UPLOAD_ID,\n",
202 | " environment_config={\n",
203 | " \"default_cot_prompt\": False,\n",
204 | " \"language\": \"R\",\n",
205 | " },\n",
206 | ")\n",
207 | "consensus_task_request = TaskRequest(\n",
208 | " name=JobNames.FINCH,\n",
209 | " query=augment_query(CONSENSUS_PROMPT, \"R\"),\n",
210 | " runtime_config=runtime_config,\n",
211 | ")\n",
212 | "consensus_task_response = client.run_tasks_until_done(\n",
213 | " [consensus_task_request], progress_bar=True, timeout=TIMEOUT\n",
214 | ")\n",
215 | "consensus_task_id = consensus_task_response[0].task_id"
216 | ]
217 | },
218 | {
219 | "cell_type": "code",
220 | "execution_count": null,
221 | "metadata": {},
222 | "outputs": [],
223 | "source": [
224 | "# Once the consensus step is done, lets's download the results\n",
225 | "client.download_file(\n",
226 | " JobNames.FINCH,\n",
227 | " trajectory_id=consensus_task_id,\n",
228 | " file_path=\"consensus_results.csv\",\n",
229 | " destination_path=\"output/consensus_results.csv\",\n",
230 | ")\n",
231 | "client.download_file(\n",
232 | " JobNames.FINCH,\n",
233 | " trajectory_id=consensus_task_id,\n",
234 | " file_path=\"top_genes.csv\",\n",
235 | " destination_path=\"output/top_genes.csv\",\n",
236 | ")"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": null,
242 | "metadata": {},
243 | "outputs": [],
244 | "source": [
245 | "# Let's use PaperQA to give us a summary of each gene\n",
246 | "top_genes_df = pd.read_csv(\"output/top_genes.csv\")\n",
247 | "display(top_genes_df.head())\n",
248 | "gene_symbols = top_genes_df[\"gene_symbol\"].tolist()\n",
249 | "pqa_tasks = [\n",
250 | " {\n",
251 | " \"name\": JobNames.CROW,\n",
252 | " \"query\": PQA_PROMPT.format(\n",
253 | " gene=gene, treatment=TREATMENT, mechanism=MECHANISM, context=CONTEXT\n",
254 | " ),\n",
255 | " }\n",
256 | " for gene in gene_symbols\n",
257 | "]\n",
258 | "pqa_task_list = await client.arun_tasks_until_done(\n",
259 | " pqa_tasks, progress_bar=True, timeout=TIMEOUT, verbose=True\n",
260 | ")"
261 | ]
262 | },
263 | {
264 | "cell_type": "code",
265 | "execution_count": null,
266 | "metadata": {},
267 | "outputs": [],
268 | "source": [
269 | "# when PQAs are done, parse answers to csv\n",
270 | "\n",
271 | "answer_list = []\n",
272 | "for task_response in pqa_task_list:\n",
273 | " try:\n",
274 | " answer = json.loads(\n",
275 | " task_response.environment_frame[\"state\"][\"state\"][\"response\"][\"answer\"][\n",
276 | " \"answer\"\n",
277 | " ]\n",
278 | " )\n",
279 | " if isinstance(answer, list):\n",
280 | " answer = answer[0]\n",
281 | " answer_list.append(answer)\n",
282 | " except Exception as e:\n",
283 | " print(f\"Error parsing answer for task {task_response.task_id}: {e}\")\n",
284 | "\n",
285 | "pqa_df = pd.DataFrame(answer_list)\n",
286 | "pqa_df.to_csv(\"output/pqa_results.csv\", index=False)"
287 | ]
288 | },
289 | {
290 | "cell_type": "code",
291 | "execution_count": null,
292 | "metadata": {},
293 | "outputs": [],
294 | "source": [
295 | "# Finally let's create a beutiful interactive plotly plot that brings all the results together\n",
296 | "# Now lets's run a single consensus step\n",
297 | "client.upload_file(\n",
298 | " JobNames.FINCH, file_path=\"output/pqa_results.csv\", upload_id=PQA_UPLOAD_ID\n",
299 | ")\n",
300 | "client.upload_file(\n",
301 | " JobNames.FINCH, file_path=\"output/consensus_results.csv\", upload_id=PQA_UPLOAD_ID\n",
302 | ")\n",
303 | "runtime_config = RuntimeConfig(\n",
304 | " max_steps=30,\n",
305 | " upload_id=PQA_UPLOAD_ID,\n",
306 | " environment_config={\n",
307 | " \"default_cot_prompt\": False,\n",
308 | " \"language\": \"PYTHON\",\n",
309 | " },\n",
310 | ")\n",
311 | "volcano_task_request = TaskRequest(\n",
312 | " name=JobNames.FINCH,\n",
313 | " query=augment_query(VOLCANO_PROMPT, \"PYTHON\"),\n",
314 | " runtime_config=runtime_config,\n",
315 | ")\n",
316 | "volcano_task_id = client.create_task(volcano_task_request)\n",
317 | "\n",
318 | "print(\n",
319 | " f\"Task running on platform, you can view progress live for our final results at:https://platform.futurehouse.org/trajectories/{volcano_task_id}\"\n",
320 | ")"
321 | ]
322 | },
323 | {
324 | "cell_type": "markdown",
325 | "metadata": {},
326 | "source": [
327 | "The final trajectory will have the reliable results of our DEA analysis in an interactive volcano plotly plot containing the top differentially expressed genes, their evidence and the evidence score! All in about 20 minutes!"
328 | ]
329 | }
330 | ],
331 | "metadata": {
332 | "kernelspec": {
333 | "display_name": ".venv",
334 | "language": "python",
335 | "name": "python3"
336 | },
337 | "language_info": {
338 | "codemirror_mode": {
339 | "name": "ipython",
340 | "version": 3
341 | },
342 | "file_extension": ".py",
343 | "mimetype": "text/x-python",
344 | "name": "python",
345 | "nbconvert_exporter": "python",
346 | "pygments_lexer": "ipython3"
347 | }
348 | },
349 | "nbformat": 4,
350 | "nbformat_minor": 2
351 | }
352 |
--------------------------------------------------------------------------------