Tech

Quick-Start with OpenAI SDK: Writing Your First Python Script to Use ChatCompletions and Manage Conversation History

When you build a chatbot, a support assistant, or even a small CLI helper, the main challenge is not getting one reply. It is keeping context across turns—so the model understands what was said earlier and stays consistent. In this quick-start, you will create a minimal Python script using the OpenAI SDK, call the Chat Completions API, and persist a conversation history to a local file. If you are learning these basics as part of a gen AI course, this workflow gives you a clean foundation you can reuse in both prototypes and production scripts.

1) Install the SDK and Configure Your API Key

Start by installing the official Python package and setting your API key via an environment variable. OpenAI’s SDKs are configured to read OPENAI_API_KEY from your system environment, which is safer than hard-coding secrets in code.

  • Install: pip install openai
  • Set the key:
    • macOS/Linux: export OPENAI_API_KEY=”…”
    • Windows PowerShell: setx OPENAI_API_KEY “…”

After setting the variable, restart your terminal (or IDE) so it picks up the new value.

See also: Next Level Tech Hub 4387955427 Performance

2) Make a First Request with the Chat Completions API

The Chat Completions API generates a response from a list of messages that represent the conversation so far. Each message includes a role and content. In other words, you “replay” the relevant conversation on every request. The API supports instruction messages too; with newer model families, developer messages are the preferred place for top-level instructions, replacing the older system message pattern.

READ ALSO  01952 983104 Call Source Breakdown: Investigating Regional Calls

OpenAI currently recommends the newer Responses API for most new projects, but Chat Completions remains a straightforward way to learn the message-based approach.

Here is a simple, single-turn call (using a model that supports the Chat Completions endpoint):

from openai import OpenAI

client = OpenAI()

messages = [

   {“role”: “developer”, “content”: “You are a concise, helpful assistant.”},

   {“role”: “user”, “content”: “Write a 2-sentence summary of what the Chat Completions API does.”},

]

completion = client.chat.completions.create(

   model=”gpt-4.1-mini”,

   messages=messages,

)

print(completion.choices[0].message.content)

If you are following along from a gen AI course, get into the habit of printing completion.usage during testing. It makes token growth visible as you add more history.

3) Manage Conversation History by Appending Messages

Chatbots feel stateful, but the API is stateless: it only sees what you send in the current request. To preserve context, append the user’s latest input, call the API, then append the assistant’s reply. On the next turn, send the entire messages list again.

Below is a tiny CLI loop that saves messages to history.json and reloads them on the next run:

import json

from pathlib import Path

from openai import OpenAI

client = OpenAI()

HISTORY_FILE = Path(“history.json”)

def load_history():

   if HISTORY_FILE.exists():

       return json.loads(HISTORY_FILE.read_text(encoding=”utf-8″))

   return [{“role”: “developer”, “content”: “You are a helpful assistant.”}]

def save_history(msgs):

   HISTORY_FILE.write_text(

       json.dumps(msgs, ensure_ascii=False, indent=2),

       encoding=”utf-8″,

   )

messages = load_history()

while True:

   user_text = input(“You: “).strip()

   if user_text.lower() in {“exit”, “quit”}:

       break

   if not user_text:

       continue

   messages.append({“role”: “user”, “content”: user_text})

   completion = client.chat.completions.create(

       model=”gpt-4.1-mini”,

       messages=messages,

   )

   assistant_text = completion.choices[0].message.content

   print(“Assistant:”, assistant_text)

   messages.append({“role”: “assistant”, “content”: assistant_text})

   save_history(messages)

This is intentionally minimal, but it demonstrates the core loop you will reuse in web apps, bots, and internal tools.

READ ALSO  01384 469737 Mobile Number Breakdown: Tracing Call Origins

4) Keep History Useful, Cheap, and Maintainable

Conversation history grows quickly, and longer prompts cost more tokens and can slow responses. A few practical strategies help:

  • Keep a fixed window: preserve the developer message plus only the last N user/assistant turns (for example, the last 10–20 turns).
  • Summarise older turns: replace a long block of history with a short summary message that captures decisions, user preferences, and open tasks.
  • Store server-side only when you truly need it: Chat Completions support a store option so stored completions can be retrieved later, but it is best used for auditing or replay rather than as your only “memory”.
  • Add basic hygiene: handle API errors and rate limits, log request IDs, and avoid putting secrets or unnecessary personal data into prompts.

These details are easy to ignore at first, but they are exactly what turns a demo into something you can run reliably—especially when you start building larger assistants after a gen AI course.

Conclusion

With a few lines of Python, you can call the Chat Completions API, send a structured messages list, and maintain conversational context by replaying prior turns. Once you are comfortable with this pattern, you can move it into Flask/FastAPI, add user IDs, and store history in a database instead of a JSON file. For many learners in a gen AI course, this is the moment the tooling stops feeling abstract and starts feeling buildable.

For more details visit us:

Name: ExcelR – Data Science, Generative AI, Artificial Intelligence Course in Bangalore

Address: Unit No. T-2 4th Floor, Raja Ikon Sy, No.89/1 Munnekolala, Village, Marathahalli – Sarjapur Outer Ring Rd, above Yes Bank, Marathahalli, Bengaluru, Karnataka 560037

READ ALSO  What's the Download Size of Technical Masterminds Games?

Phone: 087929 28623

Email: enquiry@excelr.com

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button