How to beginner · 3 min read

How to use ChatGPT for coding

Quick answer
Use the gpt-4o model via the OpenAI API to generate, debug, and explain code by sending coding prompts in chat.completions.create. Install the openai Python package, set your API key in os.environ, and send coding queries to get instant code completions.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official OpenAI Python SDK and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0

Step by step

Use the following Python code to send a coding prompt to gpt-4o and receive a code completion. This example asks ChatGPT to write a Python function that reverses a string.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a Python function to reverse a string."}]
)

print(response.choices[0].message.content)
output
def reverse_string(s):
    return s[::-1]

Common variations

  • Use gpt-4o-mini for faster, cheaper completions with slightly reduced quality.
  • Implement async calls with asyncio for concurrent requests.
  • Enable streaming responses for real-time code generation.
  • Use Anthropic's claude-3-5-sonnet-20241022 for superior coding benchmarks.
python
import asyncio
import os
from openai import OpenAI

async def main():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    response = await client.chat.completions.acreate(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Write a Python function to check if a number is prime."}]
    )
    print(response.choices[0].message.content)

asyncio.run(main())
output
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

Troubleshooting

  • If you get an authentication error, verify your OPENAI_API_KEY environment variable is set correctly.
  • For rate limit errors, reduce request frequency or upgrade your API plan.
  • If responses are incomplete, increase max_tokens parameter.
  • Check network connectivity if requests time out.

Key Takeaways

  • Use the gpt-4o model with the OpenAI Python SDK for reliable coding assistance.
  • Set your API key securely in os.environ and install the latest openai package.
  • Async and streaming calls improve efficiency for large or multiple coding tasks.
  • Adjust max_tokens and model choice based on your coding complexity and cost needs.
  • Check environment variables and API limits first when troubleshooting errors.
Verified 2026-04 · gpt-4o, gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗