OpenAI gives you free API credits when you sign up. Here is how to build a working chatbot in 10 lines.
The Complete Code
from openai import OpenAI
client = OpenAI() # uses OPENAI_API_KEY env var
print('Chat with AI (type "quit" to exit)')
history = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
while True:
user_input = input('You: ')
if user_input.lower() == 'quit':
break
history.append({'role': 'user', 'content': user_input})
response = client.chat.completions.create(model='gpt-3.5-turbo', messages=history)
reply = response.choices[0].message.content
history.append({'role': 'assistant', 'content': reply})
print(f'AI: {reply}')
Setup (3 minutes)
pip install openai
export OPENAI_API_KEY='your_key_here'
python chatbot.py
Get your key at platform.openai.com/api-keys. Free tier gives you enough credits for thousands of messages.
Make It Useful: Specialized Bots
Change the system message to create specialized assistants:
# Code reviewer
system = 'You are a senior Python developer. Review code for bugs, performance, and style.'
# SQL helper
system = 'You are a SQL expert. Convert natural language questions to SQL queries.'
# Writing assistant
system = 'You are an editor. Improve the clarity and conciseness of any text.'
Add Streaming (Feels More Natural)
stream = client.chat.completions.create(
model='gpt-3.5-turbo',
messages=history,
stream=True
)
for chunk in stream:
content = chunk.choices[0].delta.content or ''
print(content, end='', flush=True)
print()
Tokens appear one by one, like someone typing.
Cost
- GPT-3.5-turbo: ~$0.002 per 1K tokens
- Average message: ~100 tokens
- 1000 messages: ~$0.20
You can chat for months on the free credits.
What would you build with the OpenAI API?
Beyond chatbots — summarizers, translators, code generators, email writers. What is your use case?
I write about APIs, AI, and Python automation. Follow for weekly tutorials.
More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs
Top comments (0)