Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active July 14, 2026 06:49
Show Gist options
  • Select an option

  • Save luisjunco/4197c7af8cc1355d8acaaf04f83b0407 to your computer and use it in GitHub Desktop.

Select an option

Save luisjunco/4197c7af8cc1355d8acaaf04f83b0407 to your computer and use it in GitHub Desktop.
Exercise to practice sending requests to OpenAI API (Python)

Practice: Your First OpenAI API Call

Your task: write a Python script that sends a question to an LLM using the OpenAI API and prints the answer.

Iteration 1 — Research & setup (no code given)

Write a minimal script that sends a request to the OpenAI API, with the message "What's the capital of France?" and prints the response.

Notes:

  • Do some research to find the correct syntax (e.g. Google / OpenAI docs / ask an LLM for the correct syntax).
  • You'll need to set your API key as an environment variable.
  • For the model, use gpt-5.4-nano.

Iteration 2 — Make it reusable

Turn your script into a function ask(question) that takes any question as a string, sends it to the API, and returns the answer. Test it with 3 different questions.


Bonus iterations

Bonus 1: Modify ask() to accept a system prompt parameter (e.g. "Answer in one word" or "Answer like a pirate") and pass it as a system message.

Bonus 2: Wrap your API call in a try/except block to handle errors gracefully (e.g. missing/invalid API key, network issues). Print a friendly error message instead of crashing.





Solutions

Iteration 1
from openai import OpenAI
client = OpenAI()  # reads OPENAI_API_KEY from environment variable

response = client.responses.create(
    model="gpt-5.4-nano",
    input="What's the capital of France?"
)
print(response.output_text)
Iteration 2
from openai import OpenAI
client = OpenAI()

def ask(question):
    response = client.responses.create(
        model="gpt-5.4-nano",
        input=question
    )
    return response.output_text

print(ask("What's the capital of France?"))
print(ask("What's 12 * 8?"))
print(ask("Name a famous painting."))
Bonus 1
def ask(question, system=None):
    response = client.responses.create(
        model="gpt-5.4-nano",
        instructions=system,
        input=question
    )
    return response.output_text

print(ask("What's the capital of France?", system="Answer in one word"))
print(ask("What's the capital of France?", system="Answer like a pirate"))
Bonus 2
def ask(question, system=None):
    try:
        response = client.responses.create(
            model="gpt-5.4-nano",
            instructions=system,
            input=question
        )
        return response.output_text
    except Exception as e:
        return f"Something went wrong: {e}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment