Side, natural-light view of a student at a wooden dining table typing Python chatbot code on his laptop, next to an open notebook with handwritten logic flowcharts and unbranded programming books.

Build Your First AI Chatbot with Python: A Beginner Project and Code Walkthrough

A first chatbot does not need a website, a database, or a large framework. You can build a small terminal program that sends a question to an AI model, prints the reply, and carries a limited conversation history into the next turn. This project uses Python and the OpenAI Responses API; the same design can be adapted to another provider’s SDK.

Python AI chatbot: what you are building

The program will act as a study helper. A person types a question, the script sends it to a hosted model, and the program prints the returned text. The conversation history lets the next question refer to earlier turns. The model does not automatically know your course materials, and it can still make errors. As a result, treat this as a learning prototype rather than a source of authoritative answers.

This example sends requests to a paid API. ChatGPT subscriptions and API usage are billed separately. Check the current API pricing and your account’s limits before running repeated experiments. Do not put an API key in a public repository, a browser app, or a screenshot.

Set up Python and the API

  1. Install a current Python release and create a new folder for the project.
  2. Create and activate a virtual environment so this project’s packages stay separate from other Python work.
  3. Install the official SDK with python -m pip install openai.
  4. Create an API key in the provider dashboard and set it in an environment variable named OPENAI_API_KEY. Use the provider’s current key-management instructions for your operating system.
  5. Create a file named study_chatbot.py and add the code below.

Write the chatbot

from openai import OpenAI

client = OpenAI()
model = "gpt-6-astra"
history = []

print("Study helper. Type 'quit' to exit.")

while True:
    question = input("You: ").strip()

    if question.lower() in {"quit", "exit"}:
        break
    if not question:
        continue

    history.append({"role": "user", "content": question})

    response = client.responses.create(
        model=model,
        instructions=(
            "You are a study helper. Explain ideas clearly, ask a short "
            "follow-up question when useful, and say when you are unsure. "
            "Do not claim that an answer is verified unless a source is supplied."
        ),
        input=history,
    )

    answer = response.output_text
    print(f"Assistant: {answer}\n")
    history.append({"role": "assistant", "content": answer})

The SDK reads the key from the environment. The instructions value sets the chatbot’s intended behavior; the input list holds the user and assistant messages; and output_text provides the response text. The model identifier shown here is the one used in the current official quickstart. Model names and access can change, so replace it with a model available to your account if needed.

Run a small learning exercise

Start the program from the project folder, then test it with a short concept from a class. Try a second question that depends on the first, such as “Can you give me a different example?” Then ask it to explain a possible limitation. Compare the answers with your notes and write down one mistake, uncertainty, or missing qualification.

Change one part at a time. For instance, ask the assistant to answer in three bullet points, to define unfamiliar terms, or to distinguish a fact from a guess. Record a few test questions and expected behaviors before changing the instructions. This makes improvement more concrete than relying on whether the last answer sounded convincing.

Keep the prototype safe and manageable

The history list grows with every turn. For a short exercise that is fine, but a longer session can send more text and increase usage. Add a maximum history length or a deliberate summary step before turning the script into a larger application. Avoid sending personal, confidential, or restricted course information unless you have checked the provider’s data terms and your school or employer’s rules.

This script has no authentication for multiple users, no web interface, and no persistent database. If you publish it, keep secrets out of source control, add error handling, set usage limits, and review the provider’s current data-retention and privacy options. Never let a beginner demo take consequential actions on someone’s behalf.

For a no-code first step, see our ChatGPT practice guide. If you want to learn programming concepts first, review the language skills needed for your target role and compare structured options in our beginner AI course guide.

Test the chatbot before adding features

Create a small set of test prompts before you change the interface. Include a normal question, a request outside the bot’s scope, an empty input, a prompt that asks for private data, and a question with missing context. Decide what the program should do for each case. For example, it might ask a clarifying question or state that the request is unsupported. Run the same set after a code change and record any behavior that got worse.

Handle failures explicitly. A network request can time out, a key can be invalid, a service can return an error, and a user can enter an unexpectedly long message. Show a short explanation rather than exposing a raw traceback or returning a misleading answer. Keep logs free of private conversation text unless you have a clear, approved reason to store it.

Keep API credentials out of the source file and out of a public repository. Use a local environment variable or another secure method supported by your setup, and never paste a real secret into a screenshot or tutorial. Use a small usage limit while learning and review the current provider pricing before making repeated calls. This simple prototype should not be treated as a production service.

Document project setup and limits

When you share the project, include setup steps, the Python version and dependencies, a description of what the bot can do, and examples of its limits. A short test log helps another beginner understand what you measured. If the program uses an external model, identify that dependency and explain that responses can vary.

Keep the user interface honest about uncertainty. If the chatbot is only a demonstration, label it as such and avoid presenting answers as professional, legal, medical, or financial advice. Provide a way to clear a conversation if the interface stores messages, and explain whether content is sent to an external provider.

Keep your first version intentionally simple: one user input, one model response, and a visible error state. Once those parts work and you can explain them, add a feature only when you can describe the problem it solves.

Keep the test prompts with the code so you can rerun them after changing a prompt or dependency.

A good first chatbot is small enough to understand and test. Improve it by measuring whether it follows its instructions and by checking its answers against material you trust.

Keep the first version narrow enough that you can inspect the full path from question to response. Try one supported question, one out-of-scope question, and one request containing missing information. The chatbot should make uncertainty visible and avoid presenting a fabricated answer as a fact. Save a few representative inputs and outputs, remove API keys and private data, and describe what the prototype cannot do. For examples of how applied projects relate to entry-level roles, see our AI jobs guide.

Sources and further reading

Similar Posts