This is a workshop dedicated to introducing Google's Gemini API with Python and Streamlit. You'll learn how to generate an API key, authenticate with the API, make requests to the Gemini API, and output the response to the web with streamlit.
We'll first start with creating a new API key.
Here's the link: https://aistudio.google.com/app/apikey
This opens the modal to select which GC project to create an API in.
If you don't have an existing project, you can create a new one. Otherwise, select the project you'd like to create the API key for.
Copy the API key and save it for later. We'll need it soon.
Now that we've created our API key, we need to create a new folder where our Python files will be stored.
Create the folder that you want to store your Python code and files in.
This is where we'll store our source code.
- Create a new folder called:
src
- Inside the
src
folder, create a new file called:main.py
- Inside the
src
folder, create a new folder called:utils
. - Inside the
src/utils
folder, create a new file called:to_markdown.py
Done!
JSON is like a dictionary in python. It's has key-value pairs. We'll store our API key in this file.
- Create a new file called:
config.json
- Add the following content to the file:
{
"gemini": {
"api_key": "YOUR GEMINI API KEY"
}
}
Done!
Now we'll actually get into the coding!
First we need to install some libraries.
pip install -q -U google-generativeai streamlit IPython
We'll start with coding the to_markdown
function. This function will convert a text to markdown format.
import textwrap
from IPython.display import Markdown
##
## Convert a text to markdown format
##
def to_markdown(text: str):
text = text.replace("•", " *")
return Markdown(textwrap.indent(text, "> ", predicate=lambda _: True))
This is our main file. See src/app.py
for the code.
An example of running the program is shown below:
streamlit run src/app.py
Basically, you'll need the path to your app.py
file. You can get this however you like, but if you run the python file normally, streamlit will output the proper command to run.