How do I actually use the ChatGPT API to build something simple?
You use the ChatGPT API by sending a request from your code to OpenAI's servers, which then sends back a text response. It's like asking a question in the ChatGPT website, but your own program is doing the asking. You'll need an API key, which is a long password that identifies you and tracks your usage.
Let's walk through a concrete example. Say you want to build a tiny command-line tool that translates English into pirate speak. You'd write a short Python script. First, you install the 'openai' library. Then, you set your API key. The core of the script is a function that sends a 'chat completion' request. You tell the API which model to use (like 'gpt-3.5-turbo'), and you give it a list of messages. One message sets the system's role: "You are a helpful assistant that translates English into pirate speak." The next message is the user's input, like "Hello, how are you?"
The API call itself is just a few lines. It looks something like `response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages)`. The response that comes back is a JSON object, and the actual pirate greeting is nested inside it. You dig it out with something like `response['choices'][0]['message']['content']`, and then print it. The whole program might be 20 lines. I've found the trickiest part for most people isn't the code, but managing the API key securely. Never, ever paste it directly into your script. Use environment variables instead. A good tip: start with the 'gpt-3.5-turbo' model. It's incredibly cheap and fast for simple tasks like this, often costing fractions of a cent per request. You don't need the more powerful models for a fun translator. The real learning happens when you tweak that system messageāchanging the personality of your bot is surprisingly powerful and requires zero code changes.