ChatGPT is a powerful language model that can transform how developers build applications. This guide shows how to integrate ChatGPT into your projects, from obtaining an API key to coding, testing, and best practices. Follow the steps to add intelligent conversational AI to your apps.
Python, Node.js, and Java all have official SDKs. Below, we use Python 3.10+. The steps are similar for other languages.
pip install openai
1. Visit platform.openai.com.
2. Create a new project.
3. Navigate to the API section and copy your key.
Do not hardcode the key. Use environment variables.
export OPENAI_API_KEY="sk-xxxx"
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role":"system","content":"You are a helpful assistant."}]
)
print(response.choices[0].message.content)
If you see a response, you’re ready to build.
The main endpoint is /v1/chat/completions. It accepts a list of messages and returns a response.
role: system, user, or assistantcontent: Text of the message| Parameter | Description | Default |
|---|---|---|
| model | Model name, e.g., gpt-4o-mini | None |
| temperature | Creativity level 0-2 | 0.7 |
| max_tokens | Maximum output length | 256 |
| top_p | Top probability mass | 1.0 |
| frequency_penalty | Repetition penalty | 0.0 |
| presence_penalty | Topic penalty | 0.0 |
| stream | Streaming output | false |
import os, openai
openai.api_key = os.getenv("OPENAI_API_KEY")
def chat(prompt):
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{"role":"system","content":"You are a friendly coding assistant."},
{"role":"user","content":prompt}
]
)
return response.choices[0].message.content
print(chat("How do I reverse a list in Python?"))
Store conversation history in a list. Pass it each request.
history = [
{"role":"system","content":"You are a helpful assistant."}
]
def chat(prompt):
history.append({"role":"user","content":prompt})
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=history
)
history.append(response.choices[0].message)
return response.choices[0].message.content
Useful for real-time UI updates.
for chunk in openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role":"user","content":"Explain recursion."}],
stream=True
):
print(chunk.choices[0].delta.content or "", end="", flush=True)
Let the model call external APIs. Define a function schema.
functions = [
{
"name": "get_current_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type":"string"},
"unit": {"type":"string", "enum":["celsius","fahrenheit"]},
},
"required": ["location"]
}
}
]
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role":"user","content":"What's the weather in Paris?"}],
functions=functions,
function_call="auto"
)
Implement exponential backoff.
import time, random
def safe_chat(prompt, retries=5):
for i in range(retries):
try:
return chat(prompt)
except openai.error.RateLimitError:
sleep = (2 ** i) + random.uniform(0, 1)
time.sleep(sleep)
raise Exception("Rate limit exceeded")
gpt-4o for heavy workloads.Mock the API in unit tests. Example with unittest.mock in Python.
from unittest.mock import patch
@patch('openai.ChatCompletion.create')
def test_chat(mock_create):
mock_create.return_value = {"choices":[{"message":{"content":"42"}}]}
assert chat("Answer the ultimate question") == "42"
ChatGPT is a large language model trained by OpenAI to generate natural language text based on prompts.
Sign up on the OpenAI website, create a project, and copy the key from the API section.
Python, Node.js, and Java are all supported. Choose the language you are most comfortable with.
Implement exponential backoff and queue requests. Monitor your usage in the OpenAI dashboard.
Only the API is available. The model is hosted on OpenAI servers for scalability and security.
By following this guide, you can add intelligent conversational AI to your applications efficiently and responsibly. Experiment with prompts, monitor usage, and iterate to build a product that delights users.