SwiftRelay

← All sprint notes

Your First Python Chatbot: A Six-Step First Run

First lapsEN

Your first Python chatbot can live in a terminal. You type a message, a model answers, and the program remembers enough conversation to handle follow-up questions. This walkthrough builds that loop with Python, the OpenAI SDK, and SwiftRelay. You will finish with a small script you can inspect, change, and use as the starting point for a larger project.

1. Check Python before the green light

Install Python 3.10 or newer, then create a folder named python-chatbot. Open a terminal inside that folder. Check your installation with the command below. If your system uses python3 instead of python, use that command throughout this walkthrough.

python --version

Create a virtual environment so the chatbot's dependencies stay separate from your other projects:

python -m venv .venv

On macOS or Linux, activate it with:

source .venv/bin/activate

In Windows PowerShell, activate it with:

.venv\Scripts\Activate.ps1

2. Install the SDK and prepare your connection

Install the Python package that sends requests and reads responses:

python -m pip install openai

SwiftRelay is a convenient connection for this project because it works with OpenAI-compatible SDKs and bills per token. Sign up for SwiftRelay, use the small gift credit provided to new accounts, and create an API key in your account.

The OpenAI SDK needs https://api.fastapirelay.com/v1 as its base URL. Choose an available model in the dashboard and copy its exact API identifier. Gemini 2.5 Flash is one option to look for; use the identifier shown in your account rather than guessing it from the display name.

3. Store your key outside the Python file

Environment variables let your script read credentials without embedding them in source code. Replace the placeholders below with your key and chosen model identifier. Run these commands in the terminal where you will launch the chatbot.

On macOS or Linux:

export SWIFTRELAY_API_KEY="YOUR_API_KEY"

export CHATBOT_MODEL="MODEL_ID"

In Windows PowerShell:

$env:SWIFTRELAY_API_KEY="YOUR_API_KEY"

$env:CHATBOT_MODEL="MODEL_ID"

These settings apply to the current terminal session. Keep the key private, and exclude credentials from any files you commit to a repository.

4. Write the chatbot's conversation loop

Create a file named chatbot.py. Copy the following code lines in order, placing each paragraph on its own line. Preserve the indentation inside the loop and conditional blocks.

import os

from openai import OpenAI

client = OpenAI(api_key=os.environ["SWIFTRELAY_API_KEY"], base_url="https://api.fastapirelay.com/v1")

model = os.environ["CHATBOT_MODEL"]

messages = []

print("Chatbot ready. Type quit to leave.")

while True:

    text = input("You: ").strip()

    if text.lower() == "quit":

        break

    if not text:

        continue

    messages.append({"role": "user", "content": text})

    response = client.chat.completions.create(model=model, messages=messages)

    answer = response.choices[0].message.content or ""

    print("Bot:", answer)

    messages.append({"role": "assistant", "content": answer})

The messages list holds the conversation. Each request includes earlier turns, allowing the model to interpret references to previous answers. Both user messages and assistant replies must be included for that context to make sense.

5. Run a conversation and check its memory

Save the file and launch it:

python chatbot.py

Try this short sequence:

  • Type: Suggest three names for a gardening chatbot.
  • Then type: Make the second name more playful.
  • Type quit to exit.

The follow-up checks whether your script sends conversation history correctly. That history lives only in memory, so restarting the program begins a fresh conversation.

6. Fix the first errors and control growing context

If Python reports a missing environment variable, set it again in the same terminal. An authentication error usually calls for checking the API key. A model error calls for checking the dashboard identifier and availability. If the script stops after an API error, this first version exits because it has no exception handling yet.

Long conversations send progressively more text with each request, increasing token use. For this first run, restart the script when switching topics. As your next improvement, add exception handling that prints a useful error and removes the unanswered user message before accepting another prompt.

Keep reading

Back for another lap?Log in