Functions & Classes

Functions

Functions

Functions are the building blocks of reusable code. They're essential for creating AI agent tools and utilities.

Basic Syntax

def function_name(parameters) -> return_type:
    """Docstring explaining the function."""
    # function body
    return result

Parameters

  • Required: def greet(name):
  • Default: def greet(name="World"):
  • Keyword: greet(name="Alice")
  • Args/Kwargs: def func(*args, **kwargs):

Why Functions Matter for AI

  • Tool definitions — AI agents call functions as tools
  • Reusability — Write once, use everywhere
  • Testing — Easier to test isolated functions
  • Clarity — Self-documenting code

Try It Yourself

Run this code example to practice what you've learned.

example.py
1# Basic function with type hints
2def create_prompt(user_input: str, context: str = "") -> str:
3 """Create a formatted prompt for the AI model."""
4 if context:
5 return f"Context: {context}\n\nUser: {user_input}"
6 return f"User: {user_input}"
7
8# Test the function
9prompt = create_prompt("What is Python?", "Programming tutorial")
10print(prompt)
11
12# Function as an AI tool
13def get_weather(city: str, unit: str = "celsius") -> dict:
14 """
15 Get weather for a city.
16 This could be called by an AI agent as a tool.
17 """
18 # Simulated response
19 return {
20 "city": city,
21 "temperature": 22,
22 "unit": unit,
23 "condition": "sunny"
24 }
25
26# Using the tool
27weather = get_weather("San Francisco")
28print(f"\nWeather in {weather['city']}: {weather['temperature']}° {weather['condition']}")
29
30# Function with *args and **kwargs
31def log_event(event_type: str, *args, **kwargs):
32 """Flexible logging function."""
33 print(f"[{event_type}]", *args)
34 for key, value in kwargs.items():
35 print(f" {key}: {value}")
36
37log_event("API_CALL", "Calling OpenAI", model="gpt-4", tokens=100)