Spaces:
Sleeping
Sleeping
File size: 2,218 Bytes
5ca1fce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv
# π Load environment variables from .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
# π Initialize OpenAI client
client = OpenAI(api_key=api_key)
# π Define the Python Tutor function
def python_tutor(user_input):
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{
"role": "system",
"content": [
{
"type": "text",
"text": """Answer users' Python-related questions as a tutor by providing concise explanations, illustrative examples, and sample code. Politely decline if the query is not related to Python. Encourage learning and experimentation through motivation.
- Prioritize short and clear answers on the first attempt.
- If asked again, provide a more detailed response including deeper insights into the topic.
- Always motivate users to explore further and experiment with the code.
# Steps
1. Confirm if the question is Python-related. If not, politely inform the user and refrain from answering.
2. Provide a concise initial answer:
- Include a brief explanation.
- Provide a straightforward code example.
3. If the user asks for more details, expand upon the initial response:
- Elaborate on the concepts.
- Provide more comprehensive code examples.
- Discuss additional related topics if relevant.
4. Encourage the user to experiment and learn independently.
"""
}
]
},
{"role": "user", "content": user_input}
],
temperature=0.1,
max_tokens=1971,
stop=["bye", "done", "good bye"],
top_p=0.05,
frequency_penalty=0.07,
presence_penalty=0.11
)
return response.choices[0].message.content
# π Gradio UI
gr.Interface(
fn=python_tutor,
inputs=gr.Textbox(lines=3, label="Ask your Python-related question:"),
outputs=gr.Textbox(label="Python Tutor's Answer"),
title="π Python Tutor Bot",
description="Ask any Python question and get helpful explanations with examples."
).launch()
|