Member-only story
Journey to Explore Generative AI
The Shortest ChatGPT Script Tutorial
Learn and Use the ChatGPT API Under 20 Lines of Code
Published in
2 min readMar 7, 2025
To fully explore ChatGPT as a developer, learning how to use its powerful API is essential. However, when searching for simple tutorials, I often found lengthy and complex scripts.
So, I decided to create a concise script — under 20 lines of Python — to demonstrate how to interface with ChatGPT efficiently.
The Code
Let’s not talk too much. Here’s the code
import openai
openai.api_key = "API-KEY"
openai.base_url = "BASE-URL"
prompt = input("Chat: ")
try:
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
max_tokens=150,
)
print(response.choices[0].message.content.strip())
except Exception as e:
print(f"Error occurred: {e}")
By providing the API key (and optionally the base URL), you can run the script, get a input to provide a prompt to the ChatGPT API, and receive a response.
python3 sample-code-above.py
Sample output as below
Chat: Tell me something funny
Why don’t scientists trust atoms? Because they make…