Build an AI Chatbot in Python in 30 Minutes

Build an AI Chatbot in Python in 30 Minutes

## What we will build

This command-line chatbot stores recent messages, calls an OpenAI-compatible endpoint and handles errors. Because ClaudeN AI uses the OpenAI format, switching between Claude, GPT and Gemini is just a model-name change.

## Code

``python
from openai import OpenAI

client = OpenAI(api_key="YOUR_CLAUDEN_KEY", base_url="https://clauden.ai/v1")
messages = [{"role": "system", "content": "You are a concise helpful assistant."}]

while True:
user = input("You: " ).strip()
if user.lower() in {"exit", "quit"}:
break
messages.append({"role": "user", "content": user})
try:
r = client.chat.completions.create(model="claude-3-5-sonnet", messages=messages[-12:])
answer = r.choices[0].message.content
print("Bot:", answer)
messages.append({"role": "assistant", "content": answer})
except Exception as exc:
print("Request failed:", exc)
``

## Next steps

Persist the message list in SQLite, add streaming output, show token usage and route simple questions to a cheaper model. Create a ClaudeN AI account, claim the $5 free credit and run this chatbot with one API key.

Sign up and get $5 free credit

Start free

← ClaudeN AI Blog

Sign up and get $5 free credit