Skip to content

Commit 7206efe

Browse files
Merge pull request #18 from NIGMS/llm-integration
Added util folder with gemini.py, added Gemini to Submodule 1, and ad…
2 parents 346a552 + caf1f0f commit 7206efe

3 files changed

Lines changed: 169 additions & 2 deletions

File tree

GoogleCloud/README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,22 @@ When you are finished running code, you can turn off your virtual machine to pre
9595
- If you are unable to interact with your Google Cloud Storage bucket using the `gsutil` command, check your `nextflow-service-account` roles. Make sure that you have `Storage Admin` added.
9696
- If you are trying to execute a terminal command in a Jupyter code cell and it is not working, make sure that you have an `!` before the command.
9797
- e.g., `mkdir example-1` -> `!mkdir example-1`
98+
99+
## Gemini (Optional)
100+
101+
Generative AI is available for this tutorial in the form of Gemini if you would like to use it. To run it, please reference Submodule 1, or run the following code within a submodule notebook.
102+
103+
```!pip install -q google-generativeai google-cloud-secret-manager
104+
!pip install -q git+https://github.com/NIGMS/NIGMS-Sandbox-Repository-Template.git#subdirectory=llm_integrations
105+
!pip install -q ipywidgets
106+
107+
import sys
108+
import os
109+
util_path = os.path.join(os.getcwd(), 'util')
110+
if util_path not in sys.path:
111+
sys.path.append(util_path)
112+
113+
from gemini import run_gemini_widget, create_gemini_chat_widget
114+
from IPython.display import display
115+
116+
run_gemini_widget()

GoogleCloud/Submodule_1_background.ipynb

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,12 @@
4444
"\n",
4545
"6. **Introduce the Google Batch API:** Learners are introduced to the Google Batch API and its advantages for managing and executing workflows on cloud computing resources.\n",
4646
"\n",
47-
"7. **Familiarize learners with Jupyter Notebooks:** The notebook provides instructions on how to navigate and use Jupyter Notebooks, including cell types and execution order."
47+
"7. **Familiarize learners with Jupyter Notebooks:** The notebook provides instructions on how to navigate and use Jupyter Notebooks, including cell types and execution order.\n",
48+
"\n",
49+
"<div class=\"alert alert-block alert-success\">\n",
50+
" <i class=\"fa fa-hand-paper-o\" aria-hidden=\"true\"></i>\n",
51+
" <b>Tip: </b> If you're having trouble with any part of this tutorial, feel free to leverage Gemini (Google's advanced generative AI model) at the bottom of this module.\n",
52+
"</div> "
4853
]
4954
},
5055
{
@@ -508,11 +513,60 @@
508513
"\n",
509514
"Remember to proceed to the next notebook [`Submodule_2_annotation_only.ipynb`](./Submodule_2_annotation_only.ipynb) or shut down your instance if you are finished."
510515
]
516+
},
517+
{
518+
"cell_type": "markdown",
519+
"id": "82cfac8a-45f9-4e9d-8a83-0ade6fbfec81",
520+
"metadata": {},
521+
"source": [
522+
"## Gemini (Optional)\n",
523+
"--------\n",
524+
"\n",
525+
"If you're having trouble with this submodule (or others within this tutorial), feel free to leverage Gemini by running the cell below. Gemini is Google's advanced generative AI model designed to enhance the capabilities of AI applications across various domains."
526+
]
527+
},
528+
{
529+
"cell_type": "code",
530+
"execution_count": null,
531+
"id": "939b3e91-094b-4ef5-914a-4c9d1e7f3d8d",
532+
"metadata": {},
533+
"outputs": [],
534+
"source": [
535+
"# Ensure you have the necessary libraries installed\n",
536+
"!pip install -q google-generativeai google-cloud-secret-manager\n",
537+
"!pip install -q git+https://github.com/NIGMS/NIGMS-Sandbox-Repository-Template.git#subdirectory=llm_integrations\n",
538+
"!pip install -q ipywidgets\n",
539+
"\n",
540+
"import sys\n",
541+
"import os\n",
542+
"util_path = os.path.join(os.getcwd(), 'util')\n",
543+
"if util_path not in sys.path:\n",
544+
" sys.path.append(util_path)\n",
545+
"\n",
546+
"from gemini import run_gemini_widget, create_gemini_chat_widget \n",
547+
"from IPython.display import display\n",
548+
"\n",
549+
"run_gemini_widget()"
550+
]
511551
}
512552
],
513553
"metadata": {
554+
"kernelspec": {
555+
"display_name": "Python 3 (ipykernel) (Local)",
556+
"language": "python",
557+
"name": "conda-base-py"
558+
},
514559
"language_info": {
515-
"name": "python"
560+
"codemirror_mode": {
561+
"name": "ipython",
562+
"version": 3
563+
},
564+
"file_extension": ".py",
565+
"mimetype": "text/x-python",
566+
"name": "python",
567+
"nbconvert_exporter": "python",
568+
"pygments_lexer": "ipython3",
569+
"version": "3.10.16"
516570
}
517571
},
518572
"nbformat": 4,

GoogleCloud/util/gemini.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import gemini_helper.build as builder
2+
import google.generativeai as genai
3+
import ipywidgets as widgets
4+
5+
_model = None # Private module-level variable for the model
6+
7+
def _initialize_model():
8+
"""Initializes the Gemini model if not already initialized."""
9+
global _model
10+
if _model is None:
11+
try:
12+
key = builder.get_api_key()
13+
genai.configure(api_key=key)
14+
_model = genai.GenerativeModel("gemini-1.5-flash")
15+
print("Gemini model initialized successfully.")
16+
except Exception as e:
17+
print(f"Error initializing Gemini model: {e}")
18+
_model = None # Ensure it's None if initialization fails
19+
return _model
20+
21+
# --- Widget Creation and Logic ---
22+
def create_gemini_chat_widget():
23+
"""
24+
Creates and returns the Ipywidgets for a Gemini chat interface.
25+
The widgets should be displayed in the calling environment (e.g., Jupyter Notebook).
26+
"""
27+
model = _initialize_model()
28+
if not model:
29+
# If model failed to initialize, return a message widget
30+
error_message = widgets.HTML("Failed to initialize Gemini model. Please check API key and configuration.")
31+
return (error_message,) # Return as a tuple for consistency with display
32+
33+
# Create a text box for input
34+
prompt_input = widgets.Text(
35+
value='',
36+
placeholder='Type your prompt here',
37+
description='Prompt:',
38+
disabled=False
39+
)
40+
41+
# Create an output area for the response
42+
response_output = widgets.Output()
43+
44+
# Create a button to submit the prompt
45+
submit_button = widgets.Button(description="Submit")
46+
47+
# Define the function to handle the button click
48+
def on_submit_button_clicked(b):
49+
# Ensure the model is available (it should be if we reached here)
50+
if not _model:
51+
with response_output:
52+
response_output.clear_output()
53+
print("Model is not available.")
54+
return
55+
56+
with response_output:
57+
response_output.clear_output() # Clear previous output
58+
prompt_text = prompt_input.value
59+
if not prompt_text.strip():
60+
print("Please enter a prompt.")
61+
return
62+
63+
# Indicate processing
64+
print("Generating response...")
65+
try:
66+
# Generate the response using the Gemini model
67+
response = _model.generate_content(prompt_text)
68+
response_output.clear_output() # Clear "Generating response..."
69+
print(response.text)
70+
except Exception as e:
71+
response_output.clear_output() # Clear "Generating response..."
72+
print(f"Error generating content: {e}")
73+
74+
# Attach the click event handler to the button
75+
submit_button.on_click(on_submit_button_clicked)
76+
77+
# Return the widgets to be displayed by the caller
78+
return prompt_input, submit_button, response_output
79+
80+
def run_gemini_widget():
81+
"""
82+
An example "empty" function to create and immediately display the widget.
83+
"""
84+
from IPython.display import display # Import display here, as it's for notebook environment
85+
86+
widgets_to_display = create_gemini_chat_widget()
87+
if widgets_to_display: # Check if widgets were created
88+
# If only one widget is returned (e.g., an error message), display it
89+
if isinstance(widgets_to_display, tuple) and len(widgets_to_display) > 1:
90+
display(*widgets_to_display)
91+
else:
92+
display(widgets_to_display)
93+
else:
94+
print("Could not create Gemini widget.")

0 commit comments

Comments
 (0)