Submits a chat completion request through an OpenAI Python client. It sends a selected model a message history containing roles such as user, assistant, or system, then returns generated output. section 3.4 section 3.6
Generate a story
Create an OpenAI client, then call the method with model='GPT-4o' and a user message containing “Tell me a story!”. The returned object contains completion choices, a finish reason, the assistant message, and token-usage information. section 3.4
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)
Use the complete listing to see the import, client creation, request call, model selection, message history, and printed result together. section 3.4
Configure the request and interpret its result through these main elements:
- Set model to choose the language model used for completion. section 3.4
- Pass messages as a list whose entries contain role and content. section 3.4
- Read choices, finish_reason, message content, and usage from the response. section 3.4
- Adjust generation with parameters such as max_tokens, stop, temperature, top_p, n, and repetition penalties. section 3.6
