Skip to main content
Welcome to this hands-on guide on prompt engineering using the OpenAI Python client. You’ll learn how to install the package, configure the client, build a reusable prompt function, and tune generation parameters like max_tokens, temperature, top_p, and stop.

Table of Contents

  1. Prerequisites
  2. Installation
  3. Client Setup
  4. Creating the Prompt Function
  5. Running and Testing
  6. Tuning Generation Parameters
  7. Parameter Reference Table
  8. Summary
  9. Links and References

Prerequisites

  • Python 3.7+
  • An OpenAI API key
  • Basic familiarity with Python
Never commit your API key directly to source control. Use environment variables or a secrets manager in production.

Installation

Open your terminal in Visual Studio Code (Terminal → New Terminal) and install the OpenAI package:
You should see output indicating successful installation:
Clear the terminal before proceeding.

Client Setup

Create a new file named prompt_engine.py and initialize the OpenAI client. For this example, we’ll inject the API key inline—remember to switch to environment variables later.

Creating the Prompt Function

Define a function prompt_engine that sends user input to the model and returns the generated text:
The image shows a code editor with a Python script open, displaying a function definition and a pop-up with parameter suggestions. The terminal at the bottom indicates a command-line interface.

Running and Testing

Append a sample prompt and print the result:
Then run:
You’ll see the model’s comparison between Michael Jordan and LeBron James.

Tuning Generation Parameters

Fine-tuning parameters lets you control creativity, length, and focus. Here’s how to adjust the main options:

max_tokens

Controls the maximum number of tokens in the response. Increase for more detailed output:

temperature

Sets randomness:
  • 0.0 for deterministic responses
  • 1.0 for highly creative output

top_p

Limits token selection to a cumulative probability. Lower values focus the output:
top_p must be between 0 and 1 (exclusive). Values closer to 0 yield more focused results.

stop

Define one or more stop sequences to end the generation early:

Parameter Reference Table


Summary

You’ve now covered:
  • Installing the OpenAI Python SDK
  • Initializing the OpenAI client
  • Writing a generic prompt_engine function
  • Running and validating outputs
  • Fine-tuning with max_tokens, temperature, top_p, and stop
Experiment with these settings to craft prompts that deliver exactly the style and length you need.

Watch Video

Practice Lab