π οΈ Transforming LLMs into Actionable Software Agents
While large language models possess immense linguistic and reasoning capabilities, they are inherently isolated from real-time external data (e.g., live weather feeds, SQL databases, internal REST APIs). Function Calling bridges this divide by allowing developers to pass descriptions of local functions into the API. When a user asks a question requiring external data, the model intelligently determines which function to invoke and generates structured arguments conforming to your schema.
FUNCTION CALLING LIFECYCLE:
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β STEP β ACTION β DESCRIPTION β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β 1. Schema Definition β Pass `tools` array β Define local functions (name, description,β
β β in API request. β JSON Schema parameters) to the model. β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β 2. Model Decision β Model returns tool call β Instead of text, the model responds with β
β β (`finish_reason="tool_calls"`). β a function name and JSON arguments. β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β 3. Local Execution β Execute Python code β Your code executes the function locally β
β β using generated arguments. β and captures the return value. β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β 4. Final Synthesis β Send tool output back to API β Model receives execution results and β
β β for final natural language reply.β formulates the final answer to the user. β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
tools = [{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather for a given city.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"]
}
}
}]
import json
from openai import OpenAI
# 1. Define local mock function
def get_current_weather(location, unit="celsius"):
# Simulate external weather API call
weather_data = {
"Tokyo": {"temperature": "22", "unit": "celsius", "condition": "Sunny"},
"San Francisco": {"temperature": "15", "unit": "celsius", "condition": "Foggy"},
"Paris": {"temperature": "18", "unit": "celsius", "condition": "Partly Cloudy"}
}
city = location.split(",")[0].strip()
return json.dumps(weather_data.get(city, {"temperature": "20", "unit": unit, "condition": "Clear"}))
def run_conversation():
client = OpenAI()
messages = [{"role": "user", "content": "What's the weather like in Tokyo right now?"}]
# 2. Define tools available to the model
tools = [{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}]
# 3. First API call: Model decides whether to call a function
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
messages.append(response_message)
# 4. Check if model invoked a tool
if response_message.tool_calls:
available_functions = {"get_current_weather": get_current_weather}
for tool_call in response_message.tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
# Execute local function
function_response = function_to_call(
location=function_args.get("location"),
unit=function_args.get("unit", "celsius")
)
print(f"[*] Executed local function `{function_name}` with args: {function_args}")
print(f"[*] Function Output: {function_response}\n")
# Append tool response back to message history
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
})
# 5. Second API call: Model synthesizes final answer using tool output
second_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print("[+] Final Synthesized Answer:")
print(second_response.choices[0].message.content)
if __name__ == "__main__":
run_conversation()
FUNCTION CALLING BEST PRACTICES CHECKLIST:
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BEST PRACTICE β IMPLEMENTATION & OBJECTIVE β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Use Descriptive Names β Name functions intuitively (e.g., `get_user_account_balance` rather than `fn1`)β
β and Clear Descriptions β so the model accurately understands their purpose. β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Validate Function Args β Always validate parsed JSON arguments in your local code before executing β
β β database queries or external API requests. β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Handle Tool Errors β If a local function fails (e.g., database timeout), return error messages β
β β gracefully as tool outputs so the model can explain the issue to the user. β
ββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CHAPTER REVIEW CHECKLIST:
1. Function calling connects LLMs to external code by outputting structured JSON arguments.
2. The lifecycle involves defining tools, capturing model tool call requests, executing local code, and synthesizing final answers.
3. Detailed parameter descriptions and JSON schemas ensure high accuracy in argument generation.
4. Next Chapter: We cover Chapter 11 ("Defining Tool Schemas and Handling Model Tool Calls").