Using a Language Model in Code › Building a Reusable Function

Michael BrenndoerferJune 27, 20251 min read
AI Agent HandbookAll chapters
Part 2 of 15Language Models - The Brain of the Agent
Chapter 5Using a Language Model in Code › Building a Reusable Function
Reading section 5 of 15 · Building a Reusable Function · 1 minSection 5 of 15 · 1 min

Book contents

Section 5 of 15 · 1 min read

Using a Language Model in Code › Building a Reusable FunctionOne section · Sections in this chapter5 / 15 ↓

Hard-coding each API call gets tedious quickly. Let's wrap this in a function that we can reuse throughout our assistant:

In[2]:
Code
from openai import OpenAI

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))


def ask_assistant(
    user_message, system_prompt="You are a helpful personal assistant."
):
    """
    Send a message to the language model and get a response.

    Args:
        user_message: The user's question or instruction
        system_prompt: Instructions for how the assistant should behave

    Returns:
        The model's response as a string
    """
    # Using GPT-5 for general-purpose text generation
    response = client.chat.completions.create(
        model="gpt-5",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_message},
        ],
    )
    return response.choices[0].message.content


## Now we can use it easily
answer = ask_assistant("What's the capital of France?")
print(answer)

## Or with a custom system prompt
answer = ask_assistant(
    "What's the capital of France?",
    system_prompt="You are a geography teacher. Explain your answers.",
)
print(answer)

This function is the foundation of our assistant. Every time we want to ask the model something, we'll call this function (or an enhanced version of it).