How to build AI tutor with LLM
Quick answer
Build an AI tutor by integrating a large language model like
gpt-4o via the OpenAI SDK to generate interactive educational responses. Use prompt engineering to guide the model to act as a tutor, and implement conversation history for context-aware tutoring.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable for secure access.
pip install openai>=1.0 output
Collecting openai Downloading openai-1.x.x-py3-none-any.whl Installing collected packages: openai Successfully installed openai-1.x.x
Step by step
This example shows how to create a simple AI tutor that answers questions interactively using gpt-4o. It maintains conversation history to provide context-aware tutoring.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
conversation = [
{"role": "system", "content": "You are an AI tutor helping students learn effectively. Provide clear, concise explanations and ask follow-up questions to check understanding."}
]
def ask_tutor(question: str):
conversation.append({"role": "user", "content": question})
response = client.chat.completions.create(
model="gpt-4o",
messages=conversation
)
answer = response.choices[0].message.content
conversation.append({"role": "assistant", "content": answer})
return answer
if __name__ == "__main__":
print("AI Tutor: Ask me anything about math or science!")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("AI Tutor: Goodbye!")
break
reply = ask_tutor(user_input)
print(f"AI Tutor: {reply}") output
AI Tutor: Ask me anything about math or science! You: What is photosynthesis? AI Tutor: Photosynthesis is the process by which green plants use sunlight to convert carbon dioxide and water into glucose and oxygen. Would you like me to explain the chemical equation involved? You: Yes, please. AI Tutor: The chemical equation is 6CO2 + 6H2O + light energy -> C6H12O6 + 6O2. This means six molecules of carbon dioxide and six of water produce one glucose molecule and six oxygen molecules using light energy. Do you want to know how chlorophyll helps in this process?
Common variations
- Use
asynccalls withasynciofor non-blocking interaction. - Switch to smaller models like
gpt-4o-minifor cost efficiency. - Implement streaming responses for real-time tutor feedback.
- Customize the system prompt to specialize the tutor for subjects like programming or history.
import os
import asyncio
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
conversation = [
{"role": "system", "content": "You are an AI tutor specialized in programming."}
]
async def ask_tutor_async(question: str):
conversation.append({"role": "user", "content": question})
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation
)
answer = response.choices[0].message.content
conversation.append({"role": "assistant", "content": answer})
return answer
async def main():
print("AI Tutor (async): Ask your programming questions!")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("AI Tutor: Goodbye!")
break
reply = await ask_tutor_async(user_input)
print(f"AI Tutor: {reply}")
if __name__ == "__main__":
asyncio.run(main()) output
AI Tutor (async): Ask your programming questions! You: What is a Python decorator? AI Tutor: A Python decorator is a function that modifies another function or method, enhancing its behavior without changing its code. Would you like an example? You: Yes. AI Tutor: Here's a simple example: @my_decorator\ndef my_function():\n pass\nThis applies 'my_decorator' to 'my_function'. Do you want me to explain how decorators work internally?
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - For slow responses, try smaller models like
gpt-4o-minior enable streaming. - If the tutor gives irrelevant answers, refine the system prompt to be more specific about the tutor role.
- Handle rate limits by catching API exceptions and implementing retries with exponential backoff.
Key Takeaways
- Use the
OpenAISDK withgpt-4oto build an interactive AI tutor. - Maintain conversation history to provide context-aware tutoring sessions.
- Customize the system prompt to specialize the tutor for different subjects.
- Async and streaming APIs improve responsiveness and user experience.
- Proper error handling and API key management are essential for reliability.