The OpenAI Python library lets a program send prompts to OpenAI models and handle their answers in Python. It is useful when a task involves hundreds of documents: instead of submitting each one through a web interface, code can load data, generate prompts, call a model, and process the replies. section 1.3.3 section 3.0
Install the tested version with `pip install openai==1.29`. Create an OpenAI account with a payment method and a secret API key, then put the key in `OPENAI_API_KEY`. The library can read it from that environment variable when you create a client with `import openai` and `client = openai.OpenAI()`. Keep the secret key stored securely; the full key cannot be retrieved again after its creation window closes. section 3.2 section 3.3
Listing 3.1 Listing available OpenAI models
import openai #1
client = openai.OpenAI() #2
models = client.models.list() #3
for model in models.data: #4
print(model)
A first connection check: create a client, call `client.models.list()`, and inspect the returned models. A model ID identifies which model to request later. section 3.3
For chat completion, pass `client.chat.completions.create` a model ID and a `messages` list. Each message is a dictionary with `role` and `content`: `user` identifies a user message, `assistant` a model reply, and `system` can supply general guidance. The returned completion contains choices with generated messages; its reported usage includes prompt and completion tokens. section 3.4 section 3.6
Listing 3.2 Using GPT-4o for chat completion
import openai #1
client = openai.OpenAI() #2
result = client.chat.completions.create( #3
model='GPT-4o', #4
messages=[{ #5
'role':'user',
'content':'Tell me a story!'
}])
print(result)
This complete call asks GPT-4o to tell a story and prints the response. Replace the request with a task-specific prompt when integrating the call into a program. section 3.4
For sentiment classification, a prompt-building function can combine each review with the question “Is the sentiment positive or negative?” and an explicit `Positive`/`Negative` answer format. A separate function calls the model, allowing the classification pipeline to include delayed retries. Generation options also include `max_tokens` for a token limit and `temperature` for the degree of randomization. section 4.2.4 section 3.6

