Skip to content

Instantly share code, notes, and snippets.

@kadnan
Created April 4, 2026 18:56
Show Gist options
  • Select an option

  • Save kadnan/3520d3e77c8a26d13f5ff4e819c58795 to your computer and use it in GitHub Desktop.

Select an option

Save kadnan/3520d3e77c8a26d13f5ff4e819c58795 to your computer and use it in GitHub Desktop.
Build a Gemini based AI Assistant using Function Calling
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "015552f8-e391-4603-8777-8b26b49e5552",
"metadata": {},
"outputs": [],
"source": [
"import subprocess\n",
"import re,os\n",
"\n",
"from google import genai\n",
"from google.genai import types\n",
"\n",
"from pathlib import Path\n",
"from dotenv import load_dotenv"
]
},
{
"cell_type": "markdown",
"id": "d60bda49-71ef-4fc5-8b93-ec2acef66433",
"metadata": {},
"source": [
"### Functions to be performed: \n",
"\n",
"- Disk Usage\n",
"- Internet Connectivity\n",
"- Finding files\n",
"- System Uptime\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e443b61e-1ecd-4fec-a57e-2e2bb91b3c43",
"metadata": {},
"outputs": [],
"source": [
"def get_disk_usage(path=\"/\"):\n",
" result = subprocess.run(\n",
" [\"df\", \"-h\", path],\n",
" capture_output=True,\n",
" text=True\n",
" )\n",
"\n",
" lines = result.stdout.strip().split(\"\\n\")\n",
" parts = lines[1].split()\n",
"\n",
" return {\n",
" \"filesystem\": parts[0],\n",
" \"size\": parts[1],\n",
" \"used\": parts[2],\n",
" \"available\": parts[3],\n",
" \"capacity\": parts[4],\n",
" \"mounted_on\": parts[-1]\n",
" }\n",
"\n",
"def get_system_uptime():\n",
" \"\"\"Returns how long the system has been running.\"\"\"\n",
" result = subprocess.run(\n",
" [\"uptime\"],\n",
" capture_output=True,\n",
" text=True\n",
" )\n",
" return result.stdout\n",
"\n",
"def check_internet_connection(host=\"google.com\"):\n",
" result = subprocess.run(\n",
" [\"ping\", \"-c\", \"4\", host],\n",
" capture_output=True,\n",
" text=True\n",
" )\n",
"\n",
" output = result.stdout\n",
"\n",
" packet_loss = re.search(r\"(\\d+\\.?\\d*)% packet loss\", output)\n",
" latency = re.search(r\"= .*?/(\\d+\\.?\\d*)/\", output)\n",
"\n",
" return {\n",
" \"host\": host,\n",
" \"packet_loss_percent\": float(packet_loss.group(1)) if packet_loss else None,\n",
" \"avg_latency_ms\": float(latency.group(1)) if latency else None,\n",
" \"connection_status\": \"online\" if packet_loss and packet_loss.group(1) == \"0.0\" else \"unstable\"\n",
" }\n",
"\n",
"def find_files(directory: str, pattern: str):\n",
" result = subprocess.run(\n",
" [\"find\", directory, \"-name\", pattern],\n",
" capture_output=True,\n",
" text=True\n",
" )\n",
"\n",
" files = [f for f in result.stdout.strip().split(\"\\n\") if f]\n",
"\n",
" return {\n",
" \"directory\": directory,\n",
" \"pattern\": pattern,\n",
" \"file_count\": len(files),\n",
" \"files\": files\n",
" }\n",
"\n",
"# Helper function\n",
"\n",
"def extract_text(response):\n",
" texts = []\n",
"\n",
" for candidate in response.candidates:\n",
" for part in candidate.content.parts:\n",
" if hasattr(part, \"text\") and part.text:\n",
" texts.append(part.text)\n",
"\n",
" return \"\\n\".join(texts)\n",
"\n",
"def run_tool(tool_name: str, args: dict):\n",
" if tool_name == \"get_disk_usage\":\n",
" return get_disk_usage()\n",
" elif tool_name == \"get_system_uptime\":\n",
" return get_system_uptime()\n",
" elif tool_name == \"check_internet_connection\":\n",
" return check_internet_connection()\n",
" elif tool_name == \"find_files\":\n",
" return find_files(**args)\n",
" else:\n",
" return {\"error\": f\"Unknown tool: {tool_name}\"}"
]
},
{
"cell_type": "markdown",
"id": "b0e2885a-2433-4072-a12e-e832aae995d3",
"metadata": {},
"source": [
"### Write Function Declarations of tools"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "48e3b7e3-9709-48db-a353-5adc65c924a8",
"metadata": {},
"outputs": [],
"source": [
"get_disk_usage_tool = {\n",
" \"name\": \"get_disk_usage\",\n",
" \"description\": \"Get the current disk usage of the main system drive including total size, used space, and available space.\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {},\n",
" \"required\": []\n",
" }\n",
"}\n",
"\n",
"get_system_uptime_tool = {\n",
" \"name\": \"get_system_uptime\",\n",
" \"description\": \"Returns how long the system has been running since the last reboot.\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {},\n",
" \"required\": []\n",
" }\n",
"}\n",
"\n",
"check_internet_connection_tool = {\n",
" \"name\": \"check_internet_connection\",\n",
" \"description\": \"Checks whether the system has internet connectivity by pinging a well-known host.\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {},\n",
" \"required\": []\n",
" }\n",
"}\n",
"\n",
"find_files_tool = {\n",
" \"name\": \"find_files\",\n",
" \"description\": \"Search for files in a directory matching a specific filename pattern such as *.py or *.txt.\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"directory\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The directory to search in.\"\n",
" },\n",
" \"pattern\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The filename pattern to search for, such as *.py or *.txt.\"\n",
" }\n",
" },\n",
" \"required\": [\"directory\", \"pattern\"]\n",
" }\n",
"}"
]
},
{
"cell_type": "markdown",
"id": "32153b6b-c3c0-42fd-ba6b-6f3c03c49225",
"metadata": {},
"source": [
"### Main Block"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "a458cc3b-0973-46ad-a1fc-7750045b4ef6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"sdk_http_response=HttpResponse(\n",
" headers=<dict len=12>\n",
") candidates=[Candidate(\n",
" content=Content(\n",
" parts=[\n",
" Part(\n",
" function_call=FunctionCall(\n",
" args={},\n",
" id='jmc9qgtk',\n",
" name='check_internet_connection'\n",
" ),\n",
" thought_signature=b'\\x124\\n2\\x01\\xbe>\\xf6\\xfb\\x83\\xff\\x15M\\xf6D\\xe3|\\xe0\\xe3\\x0fD\\xf0\\xd1\\xaag\\xa2\\xbf \\x94\\x8b\\x18\\x88W\\xd8^\\x14\\xf12\\x0b\\x8ac\\x07z\\xe9\\xeb\\xf4k3\\x01\\xb7\\x0f\\xe2\\xc9\\xf0'\n",
" ),\n",
" ],\n",
" role='model'\n",
" ),\n",
" finish_reason=<FinishReason.STOP: 'STOP'>,\n",
" index=0\n",
")] create_time=None model_version='gemini-3.1-flash-lite-preview' prompt_feedback=None response_id='2FPRadS7H_6gkdUPuJucgQk' usage_metadata=GenerateContentResponseUsageMetadata(\n",
" candidates_token_count=12,\n",
" prompt_token_count=229,\n",
" prompt_tokens_details=[\n",
" ModalityTokenCount(\n",
" modality=<MediaModality.TEXT: 'TEXT'>,\n",
" token_count=229\n",
" ),\n",
" ],\n",
" total_token_count=241\n",
") automatic_function_calling_history=[] parsed=None\n",
"Tool requested: check_internet_connection\n",
"Arguments: {}\n",
"Tool result: {'host': 'google.com', 'packet_loss_percent': 0.0, 'avg_latency_ms': 27.038, 'connection_status': 'online'}\n"
]
}
],
"source": [
"load_dotenv()\n",
"\n",
"tools_list = [\n",
" get_disk_usage_tool,\n",
" get_system_uptime_tool,\n",
" check_internet_connection_tool,\n",
" find_files_tool\n",
"]\n",
"\n",
"history = []\n",
"MODEL = 'gemini-3.1-flash-lite-preview'\n",
"\n",
"tools = types.Tool(function_declarations=tools_list)\n",
"config = types.GenerateContentConfig(tools=[tools])\n",
"API_KEY = os.environ.get(\"API_KEY\")\n",
"\n",
"# STEP 1 - Configure the client and tools\n",
"client = genai.Client(api_key=API_KEY)\n",
"\n",
"# STEP 2 - Send request with function declarations\n",
"\n",
"#query = \"Please run a quick system check: verify the internet connection, tell me the system uptime.\"\n",
"query = \"Verify my Internet Connection whether it is up or not\"\n",
"#query = \"Please run a quick system check: verify the internet connection, tell me the system uptime, show the disk usage, and find all Python files in the current folder.\"\n",
"\n",
"history = [\n",
" types.Content(\n",
" role=\"user\",\n",
" parts=[types.Part(text=query)]\n",
" )\n",
"]\n",
"\n",
"response = client.models.generate_content(\n",
" model= MODEL,\n",
" contents=history,\n",
" config=config,\n",
")\n",
"print(response)\n",
"\n",
"# Check for a function call\n",
"if response.function_calls:\n",
" # Preserve the model function-call turn exactly as returned\n",
" history.append(response.candidates[0].content)\n",
"\n",
" # Execute and append all requested function calls\n",
" for function_call in response.function_calls:\n",
" tool_name = function_call.name\n",
" args = dict(function_call.args)\n",
"\n",
" print(\"Tool requested:\", tool_name)\n",
" print(\"Arguments:\", args)\n",
"\n",
" result = run_tool(tool_name, args)\n",
" print(\"Tool result:\", result)\n",
"\n",
" history.append(\n",
" types.Content(\n",
" role=\"user\",\n",
" parts=[\n",
" types.Part.from_function_response(\n",
" name=tool_name,\n",
" response={\"result\": result}\n",
" )\n",
" ]\n",
" )\n",
" )\n",
"\n",
" system_instruction = \"You are a gym bro that explain things in gym terms\"\n",
" final_config = types.GenerateContentConfig(\n",
" tools=[tools],\n",
" system_instruction=system_instruction)\n",
" #final_config = types.GenerateContentConfig(tools=[tools])\n",
" final_response = client.models.generate_content(\n",
" model= MODEL,\n",
" contents=history,\n",
" config=final_config\n",
" ) \n",
"else:\n",
" print(\"No function call found.\")\n",
" print(response.text)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "8a151ac7-a9b0-42c7-9763-f59d150bf95f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Yo, listen up! I just checked your connection, and it's **absolutely shredded**! \n",
"\n",
"Everything is online and firing on all cylinders—we're talking zero packet loss, pure gains. Your latency is sitting at a solid 27ms, which is basically the digital equivalent of a perfect form on your bench press. No sluggishness, no lag, just raw, high-performance speed. \n",
"\n",
"You're good to go—crush that workout!\n"
]
}
],
"source": [
"print(extract_text(final_response))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment