The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
The shortest path to a Python AI chatbot is the official OpenAI Python SDK and the Responses API: install the SDK, provide an API key securely, and send each user message to client.responses.create(). A model call can answer one message, but it does not remember earlier turns by itself. To build a chatbot that can hold a conversation, deliberately carry forward or persist conversation state; to answer from your own documents, retrieve relevant passages and include them in the model request.
What you need before you start
- Python 3.10 or newer. The official OpenAI Python library lists Python 3.10+ as supported. Check its current requirements in the OpenAI Python library README.
- An OpenAI API key. Create one through your OpenAI account, then keep it in an environment variable rather than putting it in source code, a public repository, or browser JavaScript.
- A project environment. A virtual environment keeps this project’s dependencies separate from other Python projects.
The SDK is installed with pip install openai. OpenAI identifies the Responses API as its primary API for interacting with models; its developer quickstart shows the first-request pattern.
Create a project and install the SDK
In a terminal, create a directory, enter it, and make a virtual environment:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchmkdir python-chatbot
cd python-chatbot
python -m venv .venv
Activate it before installing. On macOS or Linux:
source .venv/bin/activate
On Windows PowerShell:
.venvScriptsActivate.ps1
Then install the SDK:
python -m pip install openai
Set the API key without putting it in the program
On macOS or Linux, set the variable in the current terminal session:
#1 Best Overall
- Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
- Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
- CanaKit Turbine Black Case for the Raspberry Pi 5
- CanaKit Low Noise Bearing System Fan
- Mega Heat Sink - Black Anodized
export OPENAI_API_KEY="your_api_key"
In Windows PowerShell:
$env:OPENAI_API_KEY="your_api_key"
These session-scoped settings are convenient for a first run. For a deployed app, configure secrets through the hosting environment’s secret-management settings. Do not commit a real key in a .py file or repository. If a key is exposed, revoke it and replace it.
Make the first chatbot in Python
Save this as chatbot.py. Set OPENAI_MODEL to a model currently supported by your API account; model names and availability can change, so confirm the live model documentation before running it. The program raises a clear error if you forget either environment variable.
import os
from openai import OpenAI
api_key = os.environ.get("OPENAI_API_KEY")
model = os.environ.get("OPENAI_MODEL")
if not api_key:
raise SystemExit("Set OPENAI_API_KEY before starting the chatbot.")
if not model:
raise SystemExit("Set OPENAI_MODEL to a currently supported model.")
client = OpenAI(api_key=api_key)
while True:
try:
user_text = input("You: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nGoodbye.")
break
if user_text.lower() in {"quit", "exit"}:
print("Goodbye.")
break
if not user_text:
continue
try:
response = client.responses.create(
model=model,
input=user_text,
)
print("Bot:", response.output_text)
except Exception as exc:
print(f"Request failed: {exc}")
Set the model variable in the same terminal before launching. For example, in macOS or Linux, use export OPENAI_MODEL="your-current-model"; in PowerShell, use $env:OPENAI_MODEL="your-current-model". Then run python chatbot.py, enter a question, and type quit or exit to stop. This is a minimal command-line interface: the program sends one input string to the API, prints the returned text, and starts the next turn.
Recommended Free Tools
The exception handler keeps a request error from printing a traceback and ending the loop. During development, inspect errors carefully, but avoid logging secrets or sensitive user content. For a real app, catch expected API and network errors deliberately, present a useful message, and log operational details with appropriate privacy controls rather than treating every exception as identical.
Rank #2
- Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM)
- Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
- CanaKit Premium High-Gloss Raspberry Pi 4 Case with Integrated Fan Mount, CanaKit Low Noise Bearing System Fan
- CanaKit 3.5A USB-C Raspberry Pi 4 Power Supply (US Plug) with Noise Filter, Set of Heat Sinks, Display Cable - 6 foot (Supports up to 4K60p)
- CanaKit USB-C PiSwitch (On/Off Power Switch for Raspberry Pi 4)
Add conversation memory deliberately
Each call in the minimal example contains only the current user text. The model therefore has no automatic access to earlier turns. Choose how state should persist before extending the interface: a single request, the duration of a session, or across sessions and devices are different product requirements.
| Approach | What you do | Trade-off to consider |
|---|---|---|
| Replay a bounded message history | Keep recent user and assistant messages in your application and send them with each new request. | It is straightforward and gives you direct control over what context is sent, but you must implement storage, limits, and session handling. |
Chain with previous_response_id |
Pass the prior response ID when making a follow-up request. | It is convenient for a response chain; your application still needs to associate the right response with the right user or session. |
| Use a Conversations API object | Keep a conversation identifier and use it to continue a durable conversation. | It provides a durable identifier, so decide who can access it and how its associated state fits your retention and privacy requirements. |
For a small command-line experiment, replaying a limited history is easy to understand. Here is the central change: keep messages in the expected role/content form, append each new user message, and add the assistant’s returned text to the same list.
history = []
# For each non-empty user_text:
history.append({"role": "user", "content": user_text})
response = client.responses.create(model=model, input=history)
answer = response.output_text
history.append({"role": "assistant", "content": answer})
print("Bot:", answer)
In a longer-running app, do not let this list grow without bound. Old messages increase the amount of context sent on later turns and can crowd out the current question. Set a deliberate history policy: for example, retain a recent window, summarize older discussion, or retrieve only relevant prior facts. Those are application decisions; test them against the conversations your chatbot is meant to handle.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsOpenAI’s conversation-state guide explains the state options and reports that response objects are retained for 30 days by default, subject to documented controls and exceptions. The guide distinguishes response storage from conversation-object persistence. Before launch, review the current data controls documentation and decide what your product should store, for how long, and who can retrieve it. Do not assume that clearing your local history also deletes state held by an API feature.
Rank #3
- 【What you Get】You will get 1*Pi 5 8GB Single Board,1*RasTech Case,1*Active Cooler,1*Screwdriver,1*Installation instructions,12-month free warranty, lifetime service, 24-hour prompt and friendly response.
- 【More Connectors】There are two USB 3.0 ports(5Gbps simultaneously) and two USB 2.0 ports, which triple total bandwidth ,support any combination of up to two cameras or displays. Peak SD card performance is doubled through support for the SDR104 high-speed mode. It provides a smooth desktop experience for you. Offer Gigabit Ethernet and a PCIe interface, along with dual-band Wi-Fi and Bluetooth 5.0/BLE wireless capability. The RasTech Pi 5 Kit use the new 27W 5.1V 5A USB-C power connector.
- 【 Support Dual 4Kp60 Display 】Each of the two microHDMI sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs (requires separate M.2 HAT).
- 【 Excellent Chips And Applications】Pi 5 is a full-size Pi computer using silicon built in-house at Pi. The RP1 “southbridge” provides the bulk of the I/O capabilities for Pi 5. Pi 5 is more friendly and convenient in the development of Internet of Things, Web development, machine identification, automatic control and other electronic equipment applications and network.
- 【 Faster CPU, Better GPU 】 Pi 5 features a Broadcom BCM2712 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz, it delivers a 2–3× increase in CPU performance relative to RaspberryPi 4. The 800MHz VideoCore VII GPU is compatible to OpenGL ES 3.1 and Vulkan 1.2, substantial uplift in graphics performance. Pi 5 Offers lightning-fast CPU speed, a PCI Express interface, a Real Time Clock (RTC) and a power button and runs significantly cooler than Pi 4.
Make the chatbot answer from your documents
A model call alone does not make a private knowledge base. For document-grounded answers, use retrieval: prepare your content, find the passages most relevant to the current question, and provide those passages as context in the generation request. This is often called retrieval-augmented generation, or RAG.
- Ingest the material. Gather documents the application is allowed to use. Extract text, normalize it, retain useful titles or section labels, and record a source identifier so an answer can point back to where its context came from.
- Split into sections. Divide long text into chunks small enough to retrieve usefully. Keep headings and neighboring context where needed; chunk size and overlap depend on the structure and purpose of your corpus, so evaluate them rather than assuming one value works for every collection.
- Create embeddings and an index. Generate a vector representation for each chunk and store it alongside its text and source metadata in a searchable index. The embedding model and vector-store choice are implementation decisions; choose based on your deployment, update workflow, and evaluation results.
- Embed each question and retrieve matches. At query time, create a vector for the user’s question and use it to find relevant chunks. Tune the number and ranking of matches against representative questions. A high similarity score is not proof that a passage answers the question.
- Send only relevant context to the model. Include retrieved passages with source labels and instruct the chatbot to answer from them, cite the labels you provide, and say when the supplied evidence does not answer the question.
- Evaluate failure cases. Test questions with no matching source, conflicting passages, outdated material, and wording unlike the documents. Decide whether the app should ask a clarifying question, state that evidence is missing, or route the question elsewhere.
OpenAI’s Q&A and chatbot guidance describes the core pattern of embedding source material and questions, retrieving relevant information, and injecting the context into a response request. Retrieval quality depends on the corpus and implementation. Evaluate recall (whether useful passages are found), citation quality, corpus-update behavior, ranking, and the behavior when nothing relevant is retrieved.
Keep the prompt’s source labels attached to the text you retrieve. For example, label each passage with its document title and section, then ask the model to cite those labels in the answer. That makes it easier for a user to check an answer against its source. Do not present a citation as proof unless your application can map it back to the actual passage.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Put the Python call behind a user interface
A command-line loop is useful for verifying the model call, but a web chatbot needs a server-side endpoint that receives the user’s message, applies your session and safety rules, calls the API, and returns the answer. The browser should call your application, not OpenAI with a secret key embedded in front-end code. Keep credentials on the server and associate each conversation with an authenticated or otherwise appropriately scoped session.
Rank #4
- All-in-One Complete Kit: This SANOOV RPi 5 bundle comes with Raspberry Pi 5 4GB RAM single board, active cooler, durable ABS case and screwdriver. No extra parts needed, ready to use right out of the box for beginners and hobbyists
- Powerful Single Board Computer: Equipped with 4GB RAM and high-performance processor, delivers fast running speed for 4K playback, AI projects, programming and daily computing tasks. SANOOV for raspberry pi 5 4GB is equipped with broadcom 64 quad-core Arm Cortex A76 processor with gigabit ethernet and upgraded with IEEE 802.11ac Wi-Fi, Bluetooth 5.0 dual-band 2.4Ghz and 5Ghz and Power Over Ethernet (POE). Upgrading delivers 2-3 x speed vs Pi 4, redefining the experience
- Efficient Active Cooler: Effectively lowers operating temperature and prevents performance throttling. Runs quietly even under long-time heavy load, ensures stable operation all day long. SANOOV RPi 5 4GB kit offer an active cooler, which combines an aluminium heatsink with a high-performance PWM fan. Active cooler is fully compatible with the Pi OS, which can effectively reduce the temperature of RPi5 and ensure its good performance during long-term high load operation
- Sturdy ABS Protective Case: Well-fitted for Raspberry Pi 5 board, can be secured with 4 screws to effectively protect the Pi 5 motherboard from damage, reserves full access to all ports and buttons. SANOOV uses ABS material to produce the case, which has a softer texture and feel. Meanwhile, SANOOV case adopts a layered design for easy disassembly and installation. (Tip: The Case cannot install M.2 HAT Add on Board and Solid State Drive!)
- Wide Application & Full Compatibility: Seamlessly compatible with official OS and mainstream peripheral accessories for Raspberry Pi 5. Whether you are a beginner, student, electronics hobbyist or professional developer, this all-in-one kit meets your diverse needs. It excels in IoT projects, robotics design, retro gaming devices, home media servers and other DIY creations. Backed by a large global community, you can easily find guides, technical support and shared projects online
As you add a web framework, separate the model request from interface code. A small function that accepts the current message, session state, and optional retrieved context is easier to test than API calls scattered through route handlers. Validate incoming message size and type, handle missing or expired session state, and decide what should happen if the model request fails. Avoid returning stack traces or internal configuration to the browser.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Improve responsiveness and handle more users
Stream output for a more responsive interface
Streaming lets an application display generated text incrementally instead of waiting for the complete response. It can improve the feel of a long answer, but your interface must handle partial output, a user cancelling a turn, and a stream that ends with an error. The official SDK README documents streaming patterns; see the SDK README for the current interface.
Use the async client for concurrent work
For an application that handles concurrent requests, an asynchronous client can fit an asynchronous server better than blocking the event loop with synchronous calls. The SDK provides an async client, documented in its README. Async does not eliminate rate limits, network failures, or the need to bound concurrent work; test how your application behaves under expected traffic.
Consider Realtime for audio or multimodal interaction
If the product needs low-latency audio or multimodal turns, evaluate OpenAI’s Realtime API and its WebSocket interface rather than trying to make a text-only request loop behave like a live audio session. The SDK README describes Realtime support. Choose it because the interaction requires that interface, not simply because the application is called a chatbot.
Best Value
- Not including the Raspberry Pi 5 (8GB), the Crowpi advanced version comes with the Raspberry Pi 5
- ELECROW Black Case for the Raspberry Pi 5, CrowPi is equipped with a 9-inch HD touchscreen along with a camera; All the regular components used in DIY electronics are packed into the CrowPi development board, such as LCD, LED matrix, buzzer, light sensor, PIR sensor, ultrasonic sensor, IR sensor, etc
- Raspberry Pi Sensors: The Crowpi raspberry pi 5 programming kit is jam-packed with lots of buttons such as 19 different sensors in a tidy easy to use package; You don't have to wait and wire things
- Build Quality: Solid ABS shell and well made components in one place make it strong and convenient to travel
- Programming Lessons: This raspberry pi 5 learning kit ships with step by step instructions and provides 21 lessons to take you through identifying components reading code and running it in the terminal
Prepare the chatbot for production
A successful test prompt is not evidence that a chatbot is ready for real users. OpenAI’s deployment checklist recommends selecting a model through representative evaluations, sending a safety identifier, monitoring misalignment, preparing for traffic increases and overload, and choosing background or WebSocket modes when the workload calls for them.
- Evaluate the actual task. Build a set of representative questions and expected behaviors, including cases where the correct response is to say evidence is missing. Compare candidate models on that set before choosing one.
- Set safety and review procedures. Use a safety identifier as directed by the deployment guidance, monitor for misalignment, and define how people can report or review problematic outputs.
- Plan for overload and failures. Handle timeouts and API errors without losing the user’s message. Decide whether to retry, and avoid uncontrolled retry loops that can multiply requests.
- Choose an interaction mode to match the work. A basic request suits a turn-based text interface; streaming, asynchronous requests, background work, or WebSockets fit different latency and workload needs.
- Budget using your own usage. API cost depends on the selected model and the requests your application actually sends. Conversation history and retrieved passages add input, so measure usage in representative flows and set limits or alerts appropriate to your account.
- Review data handling. Document what conversation data the application stores, what API state it uses, who can see it, and how users can request deletion. Check current platform data controls before promising a retention behavior.
Troubleshoot common problems
| Symptom | Likely cause | What to check |
|---|---|---|
ModuleNotFoundError: No module named 'openai' |
The SDK is not installed in the Python environment running the script. | Activate the project’s virtual environment, run python -m pip install openai, and confirm that the same python runs both pip and the script. |
The program says OPENAI_API_KEY is missing |
The variable was not set in this terminal session, or the script runs in a different environment. | Set the variable in the terminal or deployment secret configuration used to launch the app. Do not fix this by hard-coding the key. |
| The API rejects the model | The configured model name may be unsupported for the account or endpoint. | Check the live API documentation and account availability, then update OPENAI_MODEL. Do not rely on a stale model name copied into a tutorial. |
| The chatbot forgets the previous turn | The new request includes only the latest user text. | Replay suitable bounded history or use the response-chaining or Conversations API approach, and verify that each session receives only its own state. |
| The answer invents a document detail | Retrieved context may be irrelevant, incomplete, conflicting, or absent; the prompt may not tell the model what to do in that case. | Inspect retrieved passages and source labels, test no-match questions, and instruct the bot to state when the provided evidence does not answer the question. |
| The web page exposes the API key | The key was placed in browser-side code or returned to the client. | Revoke the exposed key, create a replacement, and move model calls to a server-side endpoint using a secret configuration. |
Or skip the browser setup
Once your chatbot has a publicly reachable web page, you can capture it through ScreenshotNeo, a website screenshot API and MCP server. It is for capturing the page, not for generating chatbot answers. One GET request returns an image or PDF; the example below saves a WebP screenshot. Replace the sample URL with the public URL of your deployed chatbot. See the ScreenshotNeo API documentation for the current parameters and response details.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo accepts cookie or consent banners like a visitor before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up for free and try 1,000 screenshots a month with no card.
Frequently Asked Questions
Can I build the first version without a database?
Yes. A command-line prototype can call the API without a database. Add storage only when your product needs session history, durable conversations, or a document index.
Does adding memory make the chatbot remember everything indefinitely?
No. Memory is the state your application or API feature supplies and retains under its configured behavior; it is not a guarantee that every earlier detail remains available or relevant.
Is a document chatbot guaranteed to answer only from its sources?
No. Retrieval provides relevant context, but retrieval misses and unsupported answers remain possible. Test groundedness and make missing evidence an explicit expected outcome.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →

