Technical Support Documentation & Step-by-Step Execution Guide
|
Overview: |
1. System Requirements & Prerequisites
Before executing the attached agent script, verify that your
local environment meets the required technical specifications:
·
Python 3.9+: Python version 3.9 or
higher installed on your system. You can verify your version by running python
--version in your terminal.
·
Network Access: An active internet
connection to communicate with the Gemini API endpoints.
·
API Credentials: A valid Google Gemini API
Key. The script includes a fallback hardcoded key for immediate testing, but
production usage requires your own credential.
2. Step-by-Step Execution Guide
Follow these exact steps to set up and run the script on your
machine:
Step 1: Save the Code File
Copy the attached Python script code and save it into a file
named agent_calculator.py in your preferred working directory.
Step 2: Install Required
Dependencies
Open your terminal or command prompt, navigate to the folder
containing your script, and install the official Google GenAI SDK using pip:
|
pip
install google-genai |
Step 3: Configure Your API Key
(Optional)
For secure environment management, set your Gemini API key as an
environment variable before launching the script. If you skip this, the script
will prompt you interactively.
·
Windows (Command Prompt): set
GEMINI_API_KEY=your_api_key_here
·
Windows (PowerShell):
$env:GEMINI_API_KEY="your_api_key_here"
·
macOS / Linux: export
GEMINI_API_KEY="your_api_key_here"
Step 4: Run the Script
Execute the script from your terminal using Python:
|
python
agent_calculator.py |
Step 5: Interacting with the
Agent
Once running, the script will output the model name and an
example prompt. Enter your calculation query when prompted:
·
Test Query: Example Prompt: Multiply
17.5 by 8, then add 23.
·
Execution Flow: The agent will
iteratively call the calculate tool step-by-step and output the final result.
3. Troubleshooting Common Errors
If you encounter issues during execution, consult the
troubleshooting matrix below:
|
Error / Symptom |
Root Cause & Resolution |
|
ModuleNotFoundError: No module named 'google' |
The google-genai SDK is not installed in the active python
environment. Run pip install google-genai. |
|
GEMINI API ERROR: API_KEY_INVALID |
The provided API key is incorrect or expired. Generate a new
key from Google AI Studio and update your environment variable. |
|
RuntimeError: The agent did not finish within 3 tool steps. |
The model exceeded MAX_STEPS (3). Simplify the query or
increase MAX_STEPS in the script configuration. |
Support Contact: For additional
technical assistance or SDK inquiries, contact the AI Engineering Support Team.
"""
First Working AI Agent (Gemini Version)
---------------------------------------
A minimal, framework-free tool-using agent built with the
new Google GenAI SDK (google-genai).
Requirements:
Python 3.9+
pip install google-genai
Environment variable:
GEMINI_API_KEY=your_api_key_here
"""
from __future__ import annotations
import math
import os
import getpass
# Import the new SDK
from google import genai
from google.genai import types
from google.genai import errors
MODEL = os.getenv("GEMINI_MODEL", "gemini-3.6-flash")
MAX_STEPS = 3
INSTRUCTIONS = """
You are a small calculator agent.
Rules:
1. Use the calculate tool for every arithmetic operation.
2. Perform only one arithmetic step at a time.
3. Use each tool result as an observation before deciding the next step.
4. Never calculate arithmetic mentally.
5. When the user's goal is complete, return a concise final answer.
"""
def calculate(a: float, b: float, operation: str) -> float:
"""
Performs exactly one approved arithmetic operation.
Use it for every addition or multiplication.
Args:
a: The first finite number.
b: The second finite number.
operation: The arithmetic operation to perform (must be 'add' or 'multiply').
"""
if isinstance(a, bool) or isinstance(b, bool):
raise ValueError("Boolean values are not valid calculator inputs.")
a = float(a)
b = float(b)
if not math.isfinite(a) or not math.isfinite(b):
raise ValueError("Inputs must be finite numbers.")
if operation == "add":
return a + b
if operation == "multiply":
return a * b
raise ValueError(f"Unsupported operation: {operation!r}")
def run_agent(question: str, api_key: str) -> str:
"""
Run the model-tool-observation loop under
a bounded step limit using the new SDK.
"""
if not question.strip():
raise ValueError("The question cannot be empty.")
# Initialize the new Client
client = genai.Client(api_key=api_key)
# Configure tools and system instructions
config = types.GenerateContentConfig(
system_instruction=INSTRUCTIONS,
tools=[calculate]
)
# Use a Chat session to automatically handle conversation history
chat = client.chats.create(model=MODEL, config=config)
response = chat.send_message(question)
for step in range(1, MAX_STEPS + 1):
# If there are no tool requests, the model has finished.
if not response.function_calls:
final_answer = response.text
if not final_answer:
raise RuntimeError("The model returned neither a tool call nor text.")
return final_answer.strip()
print(f"\nSTEP {step}/{MAX_STEPS}")
tool_outputs = []
for tool_call in response.function_calls:
name = tool_call.name
args = tool_call.args
if name != "calculate":
print(f"TOOL ERROR: Unknown tool: {name!r}")
# Use types.Part.from_function_response for the new SDK
tool_outputs.append(
types.Part.from_function_response(
name=name,
response={"error": f"Unknown tool: {name}"}
)
)
continue
try:
result = calculate(
a=args["a"],
b=args["b"],
operation=args["operation"],
)
print(
f"TOOL: calculate("
f"a={args['a']}, "
f"b={args['b']}, "
f"operation={args['operation']!r}"
f") => {result}"
)
# Format the successful observation
tool_outputs.append(
types.Part.from_function_response(
name=name,
response={"result": result}
)
)
except (KeyError, TypeError, ValueError) as exc:
print(f"TOOL ERROR: {exc}")
# Format the error observation
tool_outputs.append(
types.Part.from_function_response(
name=name,
response={"error": str(exc)}
)
)
# Return tool observations to the model
response = chat.send_message(tool_outputs)
# Tool budget is exhausted. Ask for a final answer
# without allowing further tool calls.
response = chat.send_message(
"The tool-step budget is exhausted. Give the final answer now."
)
final_answer = response.text
if final_answer:
return final_answer.strip()
raise RuntimeError(
f"The agent did not finish within {MAX_STEPS} tool steps."
)
def main() -> None:
"""Command-line entry point."""
# Try to get the API key from the environment first
api_key = os.getenv("GEMINI_API_KEY","Your - API - Input here")
# If not found, prompt the user to paste it directly
if not api_key:
print("Could not find GEMINI_API_KEY in environment variables.")
api_key = getpass.getpass("Please paste your Gemini API Key here (input will be hidden): ").strip()
if not api_key:
raise SystemExit("No API key provided. Exiting.")
print(f"\nModel: {MODEL}")
print("Example: Multiply 17.5 by 8, then add 23.")
question = input("\nAsk: ").strip()
try:
answer = run_agent(question, api_key)
print(f"\nFINAL: {answer}")
except errors.APIError as exc:
print(f"\nGEMINI API ERROR: {exc}")
except (ValueError, RuntimeError) as exc:
print(f"\nERROR: {exc}")
except Exception as exc:
print(f"\nUNEXPECTED ERROR: {exc}")
if __name__ == "__main__":
main()