AGENT SKILL

function-calling

Registering custom Python tools, handling parallel function calls, and executing callback routines.

License 许可
MIT
最近更新
2026-06-05
Stars
★ 2
Forks
0

01 前言 Front Matter

name
function-calling
license
MIT license
metadata
{ "skill-author": "Lord1Egypt" }
description
Registering custom Python tools, handling parallel function calls, and executing callback routines.
allowed-tools
Read Write Edit Bash

03 SKILL.md 正文

Gemini Function Calling & Tool Integration Skill

Overview

This skill describes how to connect Gemini models to external tool APIs. By declaring Python functions as tools, the model returns structured tool call instructions when it needs to retrieve live data, execute calculations, or write data. The calling application executes the actual code and returns the output to Gemini to compile a final answer.


When to Use This Skill

  • Fetching live info from databases, web endpoints, or hardware sensors.
  • Performing strict computations (e.g. currency conversion, SQL executions).
  • Connecting agent workflows to system commands or external systems (like sending slack alerts or Telegram updates).

Quick Start (with runnable code examples)

import json
from google import genai

# Initialize the Gemini GenAI Client
client = genai.Client()

# 1. Define the actual tool functions in Python
def fetch_weather(location: str) -> str:
    """Retrieve the current weather status for a given city location.
    
    Args:
        location: The name of the city (e.g., Cairo, London, Tokyo)
    """
    # Simulate a database check or API call
    db = {
        "cairo": "Sunny and hot, 38°C",
        "london": "Overcast and rainy, 14°C",
        "tokyo": "Mild and humid, 22°C"
    }
    loc = location.strip().lower()
    return db.get(loc, f"Moderate and clear, 20°C in {location}")

def calculate_tax(amount: float, rate: float = 0.14) -> float:
    """Calculate the tax amount for a transaction.
    
    Args:
        amount: The base transaction money amount
        rate: The tax rate percentage decimal (default is 0.14 for 14%)
    """
    return round(amount * rate, 2)

# 2. Run the tool loop
def run_tool_use_agent(user_query: str):
    print(f"User Request: '{user_query}'")
    
    # Send functions to model as tools (Gemini reads the docstrings/types)
    response = client.models.generate_content(
        model='gemini-2.5-flash',
        contents=user_query,
        config=dict(
            tools=[fetch_weather, calculate_tax]
        )
    )
    
    # Check if the model wants to execute a function call
    function_calls = response.function_calls
    if function_calls:
        print("\n--- Gemini Requested Function Calls ---")
        history = [response.candidates[0].content]
        
        # Process each requested function call
        for call in function_calls:
            name = call.name
            args = call.args
            print(f"Executing local function '{name}' with arguments: {args}")
            
            # Route and execute locally
            if name == "fetch_weather":
                result = fetch_weather(**args)
            elif name == "calculate_tax":
                result = calculate_tax(**args)
            else:
                result = "Error: Tool not found"
                
            print(f"Result: {result}")
            
            # Append the function call result back as a tool response
            history.append({
                "role": "tool",
                "parts": [{
                    "function_response": {
                        "name": name,
                        "response": {"result": result}
                    }
                }]
            })
            
        # Send the execution history back to Gemini to generate the final text reply
        final_response = client.models.generate_content(
            model='gemini-2.5-flash',
            contents=history,
            config=dict(
                tools=[fetch_weather, calculate_tax]
            )
        )
        print("\n--- Final Grounded Output ---")
        print(final_response.text)
    else:
        print("\nGemini did not require any function calls.")
        print(response.text)

if __name__ == "__main__":
    run_tool_use_agent("I need the weather in Cairo, and please calculate the 14% tax on a $250 invoice.")

Advanced Usage

Forcing Specific Modes (Function Calling Constraints)

You can force Gemini to call a specific function, or run purely in text mode without using tools:

# Force the model to choose from tools and output a function call
response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents="Analyze cairo",
    config=dict(
        tools=[fetch_weather],
        tool_config={
            "function_calling_config": {
                "mode": "ANY" # Options: AUTO, ANY, NONE
            }
        }
    )
)

Key References


Dependencies

  • google-genai>=0.1.1

04 同仓库更多 Skills

Lord1Egypt
Lord1Egypt/ai-skillforge

zarr-python

Chunked N-D arrays for cloud storage. Compressed arrays, parallel I/O, S3/GCS integration, NumPy/Dask/Xarray compatible, for large-scale scientific computing pipelines.

★ 2
Lord1Egypt
Lord1Egypt/ai-skillforge

what-if-oracle

Run structured What-If scenario analysis with multi-branch possibility exploration. Use this skill when the user asks speculative questions like "what if...", "what would happen if...", "what are the possibilities", "explore scenarios", "scenario analysis", "possibility space", "what could go wrong", "best case / worst case", "risk analysis", "contingency planning", "strategic options", or any question about uncertain futures. Also trigger when the user faces a fork-in-the-road decision, wants to stress-test an idea, or needs to think through consequences before committing.

★ 2
Lord1Egypt
Lord1Egypt/ai-skillforge

venue-templates

Access comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.

★ 2
Lord1Egypt
Lord1Egypt/ai-skillforge

vaex

Use this skill for processing and analyzing large tabular datasets (billions of rows) that exceed available RAM. Vaex excels at out-of-core DataFrame operations, lazy evaluation, fast aggregations, efficient visualization of big data, and machine learning on large datasets. Apply when users need to work with large CSV/HDF5/Arrow/Parquet files, perform fast statistics on massive datasets, create visualizations of big data, or build ML pipelines that do not fit in memory.

★ 2
Lord1Egypt
Lord1Egypt/ai-skillforge

usfiscaldata

Query the U.S. Treasury Fiscal Data API for federal financial data including national debt, government spending, revenue, interest rates, exchange rates, and savings bonds. Access 54 datasets and 182 data tables with no API key required. Use when working with U.S. federal fiscal data, national debt tracking (Debt to the Penny), Daily Treasury Statements, Monthly Treasury Statements, Treasury securities auctions, interest rates on Treasury securities, foreign exchange rates, savings bonds, or any U.S. government financial statistics.

★ 2
Lord1Egypt
Lord1Egypt/ai-skillforge

treatment-plans

Generate concise (3-4 page), focused medical treatment plans in LaTeX/PDF format for all clinical specialties. Supports general medical treatment, rehabilitation therapy, mental health care, chronic disease management, perioperative care, and pain management. Includes SMART goal frameworks, evidence-based interventions with minimal text citations, regulatory compliance (HIPAA), and professional formatting. Prioritizes brevity and clinical actionability.

★ 2