05. Functions

Chapter 5 of 36 · 20 min

Defining Functions

def generate_prompt(system_instruction, user_input):
    """Generate a formatted prompt for an AI model."""
    return f"System: {system_instruction}\nUser: {user_input}"

prompt = generate_prompt("You are helpful.", "Explain gravity.")
print(prompt)

The docstring (triple quotes) documents what the function does. Write these.

Default Arguments

def call_model(prompt, model="gpt-4", temperature=0.7, max_tokens=100):
    """Simulate calling an AI model."""
    return {
        "model": model,
        "prompt": prompt,
        "temperature": temperature,
        "max_tokens": max_tokens,
        "response": f"[Simulated response to: {prompt[:20]}...]"
    }

# Use defaults
result = call_model("Hello")
print(result["model"])  # gpt-4

# Override specific defaults
result = call_model("Hello", temperature=0.2)

Returning Multiple Values

def parse_response(response_text):
    """Extract parts of an AI response."""
    return response_text[:50], response_text[50:100], response_text[100:]

start, middle, end = parse_response("This is a long response from an AI model.")

Keyword Arguments

Pass arguments by name for clarity:

result = call_model(
    prompt="Tell me a joke",
    model="gpt-4",
    temperature=1.0,
    max_tokens=50
)

Scope

Variables inside a function do not leak out:

def process():
    local_var = "I only exist here"
    print(local_var)

process()  # Works
# print(local_var)  # NameError

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Write a function calculate_cost(tokens, model, per_1k_tokens) that returns the cost. Add defaults for model="gpt-4" and per_1k_tokens=0.03. Call it with and without keyword arguments.