This chapter puts the theoretical simulations aside and opens the terminal. We move straight into execution: learning how to securely generate access keys, configure an isolated test environment, and write the Python script that establishes the first real connection between your local infrastructure and the brain in the Cloud.

“We’ve seen how fuzzy logic works together with rigid instructions through the Function Calling protocol. Now it’s time to leave the architecture on paper and assemble the first electrical connections: we open our test laboratories and run our first API Call.”

Welcome to the execution phase of our project. We leave the conceptual blueprints behind and build the first digital bridge between your terminal and artificial intelligence in the Cloud.


🔹Getting the API Key (Google AI Studio)

To allow your local scripts to query the Gemini model in the Cloud, the system needs a secure authentication method. This is not a traditional user password, but a unique access key called an API Key. It acts like a digital fingerprint: it allows the Cloud service to authenticate your request and apply the access restrictions associated with the key.

To start from scratch in a completely controlled environment, the setup involves three simple steps:

  • Access the platform: Go to Google AI Studio using your Google account.
  • Generate the key: In the control panel on the left, locate and click “Get API key”, followed by “Create API key in new project” to receive a fresh testing quota.
  • Absolute security rule: The platform will display a long string of characters (e.g. AIzaSy...). Copy this code immediately and store it somewhere secure. Treat your API Key as a secret: do not publish it, do not include it in code that you distribute, and do not upload it to public repositories such as GitHub.

⚠️ Addendum – September 2026 Update

Google has since changed the interface and API key management process in Google AI Studio. The steps above describe the interface used when this lab was originally created.

In the current interface, the key can be managed from the API Keys page, and a new key is generated using the Create API key option. For new users, Google may automatically create the project and API key, so the steps for creating a “new project” may no longer appear as shown in the original example.

Important: the interface change does not affect the architecture demonstrated in this chapter. We still need an API Key to authenticate the Python script with the Gemini API.

In addition, in September 2026 Google is transitioning from the older Standard API Keys to Authorization (Auth) Keys. New keys created in Google AI Studio are already generated in the new format, so new projects do not need to be adapted separately for this change.


🔹Preparing the Isolated Sandbox (Google Colab)

A golden rule in systems engineering is that you should never test unverified code directly in production or on your main server. That is why, before writing the script on your local node, we will use Google Colab — a test environment separate from your local infrastructure, hosted in the Cloud, where you can run Python instantly, directly from your browser, without any local configuration.

To help protect your project against data leaks, we will configure the environment using the platform’s built-in security feature:

  • Open Google Colab and create a new notebook (New Notebook).
  • In the toolbar on the left side of the screen, look for the key-shaped icon called “Secrets” (environment variables).
  • Add a new variable with the exact name: API_KEY. In the Value field, paste the AIza... key generated in Step 1.
  • Enable the “Notebook access” toggle. This step is critical: your Python code will be able to access the key through the Secrets system without having to place it directly in the notebook code.

🔹“The Agent’s Greeting” (The First Python Script)

With the secure access infrastructure in place, we can run the first quick test. This script installs the new official Google GenAI library, retrieves the key from Colab’s secure storage system, and performs a simple digital “handshake” with the model in the Cloud to validate the connection.

Create a new code cell in Colab and enter the following script:

# 1. Install the new official Google GenAI SDK
# Note: We use --quiet to hide the long dependency messages in Colab
!pip install --quiet google-genai

# 2. Import the new client and configure authentication

from google.genai import client
from google.colab import userdata

# Retrieve the key from the isolated "Secrets" system

api_key = userdata.get('API_KEY')

# Initialize the new modern global client according to the current standard

ai = client.Client(api_key=api_key)

# 3. Send a simple query using the recommended stable model

response = ai.models.generate_content(
model='gemini-2.5-flash',
contents='Hello! Are you ready to be my assistant?',
)

# Display the received response as free-form text

print(response.text)

When you press the Run (Play) button and the terminal returns a coherent text response (such as “Yes, absolutely!”), the basic connection is validated. The direct communication bridge has been successfully built.

⚠️ Addendum – September 2026 update

The official Google GenAI library and the way the client is initialized have evolved in the meantime. The code above is the one used and tested in the original laboratory, at the time this episode was created, and it worked correctly in the Google Colab environment at that time.

In the current version of the SDK, Google recommends initializing the client using the import from google import genai and the call genai.Client(...). Therefore, if you reproduce the laboratory today and the form presented above is no longer accepted by the installed version, you should use the current syntax documented by Google.

Important: the change is due to the evolution of the SDK, not to the principle of the demonstration. The flow remains the same: the key is securely retrieved from Google Colab, the Python client authenticates, and the script sends a request to the Gemini model in the Cloud.


🔹Defining the Contract and Enforcing the JSON Format (Function Calling)

Now that we have seen how the model responds to us like a simple chatbot in free-form text, it is time to take the step toward systems engineering. To transform Gemini into an Agent capable of running rigid commands on our self-hosted infrastructure, we need to provide it with a technical tool (a rigid contract).

Instead of letting the SDK attempt an automatic conversion of a simple Python function — an implicit process that may fail depending on the packages installed in the system — we will use an explicit and transparent approach: the explicit declaration of the function schema (Function Declaration).

With this method, we send the Gemini model a clear JSON Schema structure in which we explicitly define which parameters our local server expects (in our case, the text parameter named component). In addition, we introduce the critical 'mode': 'ANY' setting. With this, we constrain the AI to respond through a structured function call rather than generating free-form text, forcing it to generate a structured function call containing its decision to call the local function and the parameter value extracted from the user’s request.

Add a second code cell in Colab and enter the structural execution script:

# 1. Define the local function (Rigid interface for the database)
def check_hardware_stock(component: str) -> str:
    # In the next stage, this will directly query our local database
    return f"The local stock for {component} is 15 units."

# 2. Send the query and the explicit schema to the Gemini model

response = ai.models.generate_content(
model='gemini-2.5-flash',
contents='Do we still have RAM modules left in stock?',
config={
# Explicit function mapping - a clear and controllable approach
'tools': [{
'function_declarations': [{
'name': 'check_hardware_stock',
'description': 'Check the available stock for a specific hardware component.',
'parameters': {
'type': 'OBJECT',
'properties': {
'component': {
'type': 'STRING',
'description': 'The name of the hardware component (e.g. RAM, SSD).'
}
},
'required': ['component']
}
}]]
}],
# Force the model to respond strictly through a function call
'tool_config': {
'function_calling_config': {
'mode': 'ANY'
}
}
}
)

# 3. Extract and display the actual structural decision returned by the AI

if response.function_calls:
    for call in response.function_calls:
        print(f"Function to execute: {call.name}")
        print(f"Arguments sent by AI: {call.args}")
else:
    print(f"Text response: {response.text}")

When you run this second cell, you will notice that the AI no longer responds freely, but instead generates a structured function call, mapping the user’s request to the parameter required by our local server: for example, Function to execute: check_hardware_stock and Arguments: {'component': 'RAM'}.

⚠️ Addendum – September 2026 update

The Gemini API has evolved in the meantime, and Google currently also provides a newer interface for interacting with models. However, the demonstration above uses the Generate Content API and the classic Function Calling mechanism, which represent exactly the flow used in the original laboratory.

The concept remains unchanged: the model receives the tool description, decides which function needs to be called, and generates a structured function call; execution of the function remains within the application that integrates the model.


💡 The “Ballerina and Music” Analogy (Execution Logic)It is essential to understand the micro-mechanism under the hood so you do not fall into the trap of the myth that AI magically controls your computer. The model in the Cloud does not have direct access to your server and cannot run the Python function itself.

When you send a query such as “Do we still have RAM modules left in stock?”, the fuzzy brain in the Cloud realizes that it does not have access to this current information from your local infrastructure, but notices in the contract that it has a tool called check_hardware_stock available.

At that moment, the model stops generating ordinary text and sends back to your local application a structured function call. The diagnostic message sounds something like this: “I cannot read your server, but please, Local Agent, run the check_hardware_stock function with the component=’RAM’ parameter and send me the raw result back.” Your local application is the one that executes the rigid code, retrieves the result, and resumes the music, sending the data back to the Cloud to formulate the final response.

🛠️ What’s Next in Episode 5?

The Cloud laboratory has fulfilled its mission: the Function Calling contract has been successfully validated. Now it is time to leave the protected environment of Google Colab and move the entire structure onto our real hardware, in production.

In the next episode, we move on to the physical implementation. We will move directly into the terminal of our local virtual machine. We will natively install the MariaDB database server, populate the inventory tables, and configure the local Python environment in which our Agent will run permanently and autonomously 24/7. Get ready, we’re taking down the sandbox and building the local infrastructure directly on the server!

Your infrastructure has established its first secure connection. The hands and the brain have begun communicating through clear protocols.

Stay Free! Stay Hidden! Stay Autonomous!


⚙️ Appendix: AI Engineering Micro-Course (Technical Clarifications)

  • API Key (Application Programming Interface Key): A unique code used by a computer program to identify itself to an external API, functioning as an authentication method. The API Key must be treated as a secret and protected against accidental exposure.
  • Sandbox: A computing environment separated from the production infrastructure, within which software code can be run and tested without being executed directly on the main system.
  • Secrets / Environment Variables: Dynamic variables stored outside the source code, used to pass credentials, API Keys, passwords, or other secrets to an application, reducing the risk of accidental exposure on public platforms such as GitHub.
  • JSON Request (JavaScript Object Notation): A standardized format for representing and transferring data, based on structured text in key-value pairs, easy for humans to read and for computers to process. In our architecture, such structures can carry information between the local application and the service in the Cloud.
  • Automated Function Calling in the SDK: In newer versions of the Google GenAI SDK, part of the mechanism we built manually in this laboratory can be automated. The SDK can start from a Python function and generate the structure required for the model to use it as a tool, and in certain modes it can also manage the calling and execution cycle. In our laboratory, we intentionally chose the explicit approach: we manually defined the contract, let the model generate the function call, and executed the function locally. This allows us to clearly see what happens between the “brain” in the Cloud and the “hands” of the Local Agent.