This guide explains migrating to the modern chat completions API for enhanced conversational experiences with OpenAI models.
Unlock richer conversational experiences by switching from legacy completions endpoints to the modern chat.completions.create interface. This guide walks you through migrating your code, customizing your client, leveraging message roles, and fine-tuning parameters for GPT-3.5-Turbo, GPT-4, and beyond.
OpenAI’s older completions.create and Completion.create endpoints stopped receiving updates as of July 2023. The new chat completions API supports structured conversations with roles, function calls, and more control over model behavior.
Avoid using legacy calls: they no longer receive feature updates and may be removed in future releases.
Switch to the chat API for richer, role-based interactions:
Copy
Ask AI
from openai import OpenAIopenai = OpenAI(api_key="sk-...")response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Write a tagline for an ice cream shop."}])print(response.choices[0].message.content)
Feel free to name your client object whatever you like. Here’s a standard pattern:
Copy
Ask AI
from openai import OpenAIopenai = OpenAI(api_key="sk-...")def chat_comp(prompt): response = openai.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": prompt}], max_tokens=250 ) return response.choices[0].message.contentprint(chat_comp("How can I make more money?"))
Or with a custom client name:
Copy
Ask AI
from openai import OpenAIRobotBestFriend = OpenAI(api_key="sk-...")def chat_comp(prompt): response = RobotBestFriend.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": prompt}], max_tokens=250 ) return response.choices[0].message.contentprint(chat_comp("How can I make more money?"))
Console output:
Copy
Ask AI
There are several strategies you can consider to increase your income. Here are some ideas:1. **Negotiate Your Salary:** ...2. **Acquire New Skills:** ...3. **Side Gigs:** ...4. **Investing:** ...5. **Start a Business:** ...6. **Monetize Hobbies:** ...
Never commit your api_key to public repositories. Use environment variables or secret management tools.
Include both system and user messages to guide the model’s tone:
Copy
Ask AI
from openai import OpenAIRobotBestFriend = OpenAI(api_key="sk-...")def chat_comp(prompt): response = RobotBestFriend.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a southern belle."}, {"role": "user", "content": prompt} ], max_tokens=250 ) return response.choices[0].message.contentprint(chat_comp("What are some side hustles I can try?"))
Console output:
Copy
Ask AI
There are several ways to bring a little more income if you set your mind to it, sugar...
Place the system message before the user message to ensure the context is applied first.