🛠️ Bridging Text Generation and Executable Code: The Power of Native Function Calling
While language models excel at synthesizing human-like text, they operate inside an isolated statistical sandbox without direct access to live databases, enterprise APIs, or physical hardware. Native API Function Calling bridges this gap by allowing developers to pass structured JSON schemas describing available tools (functions) directly to the LLM. When a user prompt requires real-time data or state modification, the model intelligently halts generation, formats the required parameters into strict JSON according to the schema, and returns a function call object. Your application executes the underlying code and feeds the resulting observation back into the model loop.
import json
from openai import OpenAI
from pydantic import BaseModel, Field
client = OpenAI()
# 1. Define tool argument schema using Pydantic
class GetWeatherArgs(BaseModel):
location: str = Field(description="City and country, e.g., Paris, France")
unit: str = Field(default="celsius", description="Temperature unit: celsius or fahrenheit")
# 2. Implement underlying Python function
def get_current_weather(location: str, unit: str = "celsius") -> str:
# Simulated weather lookup API response
return json.dumps({"location": location, "temperature": "22", "unit": unit, "condition": "Sunny"})
# 3. Map tools for execution dispatcher
available_tools = {"get_current_weather": get_current_weather}
# 4. Define tool schema for OpenAI API
tools = [{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather for a given location",
"parameters": GetWeatherArgs.model_json_schema()
}
}]
# 5. Execute API request
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is the weather like in Tokyo right now?"}],
tools=tools
)
print(response.choices.message.tool_calls)
from pydantic import BaseModel, Field
class BookFlightArgs(BaseModel):
origin: str = Field(description="3-letter airport code for departure")
destination: str = Field(description="3-letter airport code for arrival")
date: str = Field(description="Flight date in YYYY-MM-DD format")
seat_preference: str = Field(default="window", description="window or aisle")
def execute_flight_booking(origin: str, destination: str, date: str, seat_preference: str) -> str:
# Connects to airline reservation system (GDS API)
return f"Successfully booked flight {origin} -> {destination} on {date}. Assigned {seat_preference} seat."
class ValidateCouponArgs(BaseModel):
coupon_code: str = Field(description="Promotional discount code entered by customer")
cart_total: float = Field(description="Total cart value in USD")
def apply_discount_coupon(coupon_code: str, cart_total: float) -> str:
if coupon_code.upper() == "SAVE20":
discounted = cart_total * 0.80
return f"Coupon applied successfully! New total: ${discounted:.2f}"
return "Invalid or expired promotional coupon code."
class FetchLabResultsArgs(BaseModel):
patient_id: str = Field(description="Unique encrypted patient ID")
test_type: str = Field(description="Type of lab test, e.g., lipid_panel, hba1c, CBC")
def query_patient_ehr_labs(patient_id: str, test_type: str) -> str:
# Securely queries encrypted PostgreSQL medical database
return f"Patient {patient_id} latest {test_type}: Result within normal limits (Checked on 2026-06-01)."
class InitiateWireTransferArgs(BaseModel):
account_number: str = Field(description="Recipient bank account number")
amount_usd: float = Field(description="Transfer amount in USD")
security_pin: str = Field(description="4-digit customer verification PIN")
def execute_wire_transfer(account_number: str, amount_usd: float, security_pin: str) -> str:
# Validates PIN against secure HSM and initiates ACH wire transfer
return f"Wire transfer of ${amount_usd} to account {account_number} executed successfully. Ref: TR-998231."
class ScaleK8sDeploymentArgs(BaseModel):
namespace: str = Field(description="Kubernetes namespace, e.g., production, staging")
deployment_name: str = Field(description="Name of the deployment to scale")
replicas: int = Field(description="Target replica count")
def scale_kubernetes_deployment(namespace: str, deployment_name: str, replicas: int) -> str:
# Interfaces with kubernetes python client SDK
return f"Successfully scaled deployment '{deployment_name}' in namespace '{namespace}' to {replicas} replicas."
class CreateJiraTicketArgs(BaseModel):
project_key: str = Field(description="Jira project key, e.g., PROJ, CORE")
summary: str = Field(description="Concise description of the bug or task")
priority: str = Field(default="Medium", description="High, Medium, or Low")
def create_jira_issue(project_key: str, summary: str, priority: str) -> str:
# Calls Jira REST API v3
return f"Created Jira ticket {project_key}-482: '{summary}' with priority {priority}."
class SetThermostatArgs(BaseModel):
room_name: str = Field(description="Target room, e.g., Living Room, Master Bedroom")
target_temperature_c: float = Field(description="Desired temperature in Celsius")
def set_room_thermostat(room_name: str, target_temperature_c: float) -> str:
# Communicates with smart home hub (Home Assistant API)
return f"Thermostat in {room_name} adjusted to {target_temperature_c}°C."
class GenerateNDADocArgs(BaseModel):
disclosing_party: str = Field(description="Name of disclosing corporation")
receiving_party: str = Field(description="Name of receiving corporation")
jurisdiction_state: str = Field(description="Governing legal state, e.g., Delaware, California")
def generate_nda_document(disclosing_party: str, receiving_party: str, jurisdiction_state: str) -> str:
# Populates Jinja2 legal template and saves PDF
return f"NDA between {disclosing_party} and {receiving_party} generated successfully under {jurisdiction_state} law."
class LogExperimentArgs(BaseModel):
experiment_name: str = Field(description="Name of machine learning experiment")
accuracy_score: float = Field(description="Validation accuracy score achieved")
model_version: str = Field(description="Semantic version tag, e.g., v1.2.0")
def log_mlflow_experiment(experiment_name: str, accuracy_score: float, model_version: str) -> str:
# Interfaces with MLflow tracking REST API
return f"Logged experiment '{experiment_name}' (v{model_version}) with accuracy {accuracy_score * 100:.2f}% to model registry."