from smolagents import CodeAgent, tool import yaml from tools.final_answer import FinalAnswerTool import random # Mock Model that works without external API calls class LocalModel: def __init__(self): self.max_tokens = 2096 self.temperature = 0.7 self.model_id = 'local-model' def generate(self, messages, **kwargs): # Simple response generation without external API class Response: def __init__(self, content): self.content = content return Response("Using local processing for English tutoring.") @tool def explain_word(word: str) -> str: """Explains an English word with definition, pronunciation, examples, and usage tips. Args: word: The English word to explain Returns: A comprehensive explanation of the word """ # Enhanced word database with common English words word_database = { "hello": { "definition": "A greeting used when meeting someone or starting a conversation", "pronunciation": "heh-LOH", "part_of_speech": "interjection, noun", "examples": [ "Hello, how are you today?", "She said hello to her neighbor.", "A friendly hello can brighten someone's day." ], "synonyms": ["hi", "greetings", "salutations"], "usage_tip": "Used as a casual greeting in informal situations or as a polite greeting in formal situations." }, "beautiful": { "definition": "Pleasing to the senses or mind; attractive in appearance", "pronunciation": "BYOO-ti-ful", "part_of_speech": "adjective", "examples": [ "The sunset was absolutely beautiful.", "She has beautiful eyes.", "The garden looks beautiful in spring." ], "synonyms": ["lovely", "gorgeous", "attractive", "stunning"], "usage_tip": "Can describe physical appearance, nature, art, or abstract concepts like music." }, "learn": { "definition": "To gain knowledge or skill through study, experience, or instruction", "pronunciation": "lurn", "part_of_speech": "verb", "examples": [ "I want to learn English.", "Children learn quickly.", "She learned to play the piano." ], "synonyms": ["study", "acquire", "master", "understand"], "usage_tip": "Often followed by 'to' + verb (learn to speak) or 'about' + noun (learn about history)." }, "great": { "definition": "Of an extent, amount, or intensity considerably above average; excellent", "pronunciation": "grayt", "part_of_speech": "adjective", "examples": [ "She did a great job on the project.", "The Great Wall of China is amazing.", "Great! Let's start the lesson." ], "synonyms": ["excellent", "wonderful", "fantastic", "outstanding"], "usage_tip": "Can be used to describe size, quality, or as an exclamation of approval." }, "friend": { "definition": "A person you know well and regard with affection and trust", "pronunciation": "frend", "part_of_speech": "noun", "examples": [ "She is my best friend.", "I made a new friend at school.", "Friends help each other." ], "synonyms": ["buddy", "pal", "companion", "mate"], "usage_tip": "Friends are people you choose to spend time with and share experiences." }, "happy": { "definition": "Feeling or showing pleasure or contentment", "pronunciation": "HAP-ee", "part_of_speech": "adjective", "examples": [ "I'm happy to see you!", "The children look happy playing.", "Happy birthday to you!" ], "synonyms": ["joyful", "cheerful", "delighted", "glad"], "usage_tip": "Used to describe positive emotions and feelings of joy." } } word_lower = word.lower().strip() if word_lower in word_database: info = word_database[word_lower] response = f"## Word: {word.capitalize()}\n\n" response += f"**Definition:** {info['definition']}\n\n" response += f"**Pronunciation:** /{info['pronunciation']}/\n\n" response += f"**Part of Speech:** {info['part_of_speech']}\n\n" response += f"**Examples:**\n" for example in info['examples']: response += f"- {example}\n" response += f"\n**Synonyms:** {', '.join(info['synonyms'])}\n\n" response += f"**Usage Tip:** {info['usage_tip']}" return response else: return f"## Word: {word.capitalize()}\n\nI don't have detailed information about '{word}' in my current database. Here are some suggestions:\n\n**How to learn about new words:**\n- Look it up in a dictionary\n- Use it in sentences\n- Find synonyms and antonyms\n- Practice pronunciation\n- Read it in context\n\n**Available words in my database:**\nhello, beautiful, learn, great, friend, happy\n\nWould you like me to explain one of these words or help with grammar lessons?" @tool def grammar_lesson(topic: str) -> str: """Provides grammar lessons on various English topics. Args: topic: The grammar topic to explain (present_tense, articles, prepositions, etc.) Returns: A detailed grammar lesson with examples """ grammar_lessons = { "present_tense": { "title": "Present Tense", "explanation": "The present tense describes actions happening now or habitual actions.", "types": [ { "name": "Simple Present", "form": "Subject + verb (base form)", "examples": ["I eat breakfast every morning.", "She works at a bank.", "They live in New York."], "usage": "For habits, facts, and general truths" }, { "name": "Present Continuous", "form": "Subject + am/is/are + verb-ing", "examples": ["I am eating lunch now.", "She is working on a project.", "They are watching TV."], "usage": "For actions happening right now" } ] }, "articles": { "title": "Articles (a, an, the)", "explanation": "Articles are words that introduce nouns. English has three articles: 'a', 'an', and 'the'.", "types": [ { "name": "Indefinite Articles (a, an)", "form": "'a' before consonant sounds, 'an' before vowel sounds", "examples": ["a book", "an apple", "a university", "an hour"], "usage": "For non-specific, countable singular nouns" }, { "name": "Definite Article (the)", "form": "'the' before specific nouns", "examples": ["the book I'm reading", "the sun", "the United States"], "usage": "For specific nouns, unique things, or previously mentioned items" } ] }, "prepositions": { "title": "Prepositions (in, on, at, etc.)", "explanation": "Prepositions show relationships between words, often indicating time, place, or direction.", "types": [ { "name": "Prepositions of Time", "form": "in, on, at", "examples": ["in 2023", "on Monday", "at 3 o'clock", "in the morning"], "usage": "in (months/years), on (days/dates), at (specific times)" }, { "name": "Prepositions of Place", "form": "in, on, at, under, above", "examples": ["in the house", "on the table", "at school", "under the bed"], "usage": "Describe where something is located" } ] }, "past_tense": { "title": "Past Tense", "explanation": "Past tense describes actions that happened before now.", "types": [ { "name": "Simple Past", "form": "Subject + verb-ed (regular) or irregular form", "examples": ["I walked to school.", "She ate dinner.", "They went home."], "usage": "For completed actions in the past" }, { "name": "Past Continuous", "form": "Subject + was/were + verb-ing", "examples": ["I was reading a book.", "They were playing soccer.", "She was cooking dinner."], "usage": "For ongoing actions in the past" } ] } } topic_lower = topic.lower().replace(" ", "_") if topic_lower in grammar_lessons: lesson = grammar_lessons[topic_lower] response = f"## {lesson['title']}\n\n" response += f"{lesson['explanation']}\n\n" for grammar_type in lesson['types']: response += f"### {grammar_type['name']}\n" response += f"**Form:** {grammar_type['form']}\n" response += f"**Usage:** {grammar_type['usage']}\n" response += f"**Examples:**\n" for example in grammar_type['examples']: response += f"- {example}\n" response += "\n" return response else: available_topics = list(grammar_lessons.keys()) return f"I don't have a lesson on '{topic}'. Here are available grammar topics:\n\n" + \ "\n".join([f"- {topic.replace('_', ' ').title()}" for topic in available_topics]) + \ "\n\nPlease choose one of these topics for a detailed lesson." @tool def practice_exercise(exercise_type: str) -> str: """Generates practice exercises for English learning. Args: exercise_type: Type of exercise (vocabulary, grammar, sentence_building) Returns: A practice exercise with questions """ exercises = { "vocabulary": [ { "question": "Choose the correct word to complete the sentence:", "sentence": "The weather is very _____ today.", "options": ["beautiful", "beautifully", "beauty", "beautify"], "correct": "beautiful", "explanation": "'Beautiful' is an adjective that describes the noun 'weather'." }, { "question": "What is the opposite of 'difficult'?", "options": ["easy", "hard", "complex", "challenging"], "correct": "easy", "explanation": "'Easy' is the antonym of 'difficult'." }, { "question": "Choose the correct word:", "sentence": "I am _____ to meet you.", "options": ["happy", "sadly", "anger", "beautiful"], "correct": "happy", "explanation": "'Happy' is an adjective describing how you feel." } ], "grammar": [ { "question": "Choose the correct article:", "sentence": "I saw _____ elephant at the zoo.", "options": ["a", "an", "the", "no article"], "correct": "an", "explanation": "Use 'an' before words starting with vowel sounds. 'Elephant' starts with 'e'." }, { "question": "Select the correct tense:", "sentence": "She _____ to school every day.", "options": ["go", "goes", "going", "went"], "correct": "goes", "explanation": "For third person singular in simple present, add 's' to the verb." }, { "question": "Choose the correct past tense:", "sentence": "Yesterday, I _____ a movie.", "options": ["watch", "watched", "watching", "will watch"], "correct": "watched", "explanation": "For past tense of regular verbs, add '-ed' to the base form." } ], "sentence_building": [ { "question": "Arrange these words to make a correct sentence:", "words": ["I", "every", "morning", "coffee", "drink"], "correct": "I drink coffee every morning.", "explanation": "Subject + verb + object + time expression is a common sentence pattern." }, { "question": "Complete the sentence with the correct word order:", "sentence": "Yesterday, [beautiful/very/a/saw/I/movie]", "correct": "Yesterday, I saw a very beautiful movie.", "explanation": "Time + subject + verb + article + adverb + adjective + noun" }, { "question": "Build a sentence with these words:", "words": ["friend", "my", "happy", "is", "very"], "correct": "My friend is very happy.", "explanation": "Possessive + noun + verb + adverb + adjective" } ] } if exercise_type in exercises: exercise = random.choice(exercises[exercise_type]) response = f"## {exercise_type.title()} Practice\n\n" response += f"**{exercise['question']}**\n\n" if 'sentence' in exercise: response += f"Sentence: {exercise['sentence']}\n\n" if 'words' in exercise: response += f"Words to arrange: {', '.join(exercise['words'])}\n\n" if 'options' in exercise: response += "Options:\n" for i, option in enumerate(exercise['options'], 1): response += f"{i}. {option}\n" response += "\n" response += f"**Correct Answer:** {exercise['correct']}\n\n" response += f"**Explanation:** {exercise['explanation']}" return response else: return f"Available exercise types: vocabulary, grammar, sentence_building\n\nPlease choose one of these types for practice." # Setup with local processing (no external API needed) final_answer = FinalAnswerTool() # Create a simple non-API based agent class SimpleEnglishTutor: def __init__(self): self.tools = { 'explain_word': explain_word, 'grammar_lesson': grammar_lesson, 'practice_exercise': practice_exercise, 'final_answer': final_answer } def run(self, query): query_lower = query.lower() # Route queries to appropriate tools if 'explain' in query_lower and 'word' in query_lower: # Extract word from query words = query.split() for i, word in enumerate(words): if word.lower() == 'word' and i + 1 < len(words): target_word = words[i + 1].strip("'\"") return explain_word(target_word) return "Please specify a word to explain. Example: 'Explain the word great'" elif 'grammar' in query_lower or 'lesson' in query_lower: if 'present' in query_lower or 'tense' in query_lower: return grammar_lesson('present_tense') elif 'article' in query_lower: return grammar_lesson('articles') elif 'preposition' in query_lower: return grammar_lesson('prepositions') elif 'past' in query_lower: return grammar_lesson('past_tense') else: return grammar_lesson('present_tense') # default elif 'exercise' in query_lower or 'practice' in query_lower: if 'vocabulary' in query_lower: return practice_exercise('vocabulary') elif 'grammar' in query_lower: return practice_exercise('grammar') elif 'sentence' in query_lower: return practice_exercise('sentence_building') else: return practice_exercise('vocabulary') # default else: # General help return """## Welcome to English Tutor! 🇬🇧 I can help you with: **📚 Word Explanations** - Ask: "Explain the word [word]" - Available words: hello, beautiful, learn, great, friend, happy **📖 Grammar Lessons** - Present Tense - Articles (a, an, the) - Prepositions - Past Tense **✏️ Practice Exercises** - Vocabulary practice - Grammar exercises - Sentence building **Examples:** - "Explain the word great" - "Give me a grammar lesson on articles" - "I want vocabulary practice" How can I help you improve your English today?""" # Create agent instance agent = SimpleEnglishTutor() # Create a simple Gradio UI try: import gradio as gr def create_ui(): with gr.Blocks(theme=gr.themes.Soft(), title="English Tutor AI") as demo: gr.Markdown("# 🇬🇧 English Tutor AI") gr.Markdown("Improve your English with AI assistance! No external API required.") with gr.Tab("Word Explanation"): with gr.Row(): word_input = gr.Textbox( label="Enter an English word", placeholder="e.g., beautiful, learn, hello, great, friend, happy" ) word_btn = gr.Button("Explain Word", variant="primary") word_output = gr.Markdown() def explain_word_handler(word): if word: return agent.run(f"Explain the word {word}") return "Please enter a word to explain." word_btn.click( explain_word_handler, inputs=[word_input], outputs=[word_output] ) with gr.Tab("Grammar Lessons"): with gr.Row(): grammar_topic = gr.Radio( ["Present Tense", "Articles", "Prepositions", "Past Tense"], label="Choose a grammar topic" ) grammar_btn = gr.Button("Get Lesson", variant="primary") grammar_output = gr.Markdown() def grammar_handler(topic): if topic: return agent.run(f"Give me a grammar lesson on {topic}") return "Please select a grammar topic." grammar_btn.click( grammar_handler, inputs=[grammar_topic], outputs=[grammar_output] ) with gr.Tab("Practice Exercises"): with gr.Row(): exercise_type = gr.Radio( ["Vocabulary", "Grammar", "Sentence Building"], label="Choose exercise type" ) exercise_btn = gr.Button("Get Exercise", variant="primary") exercise_output = gr.Markdown() def exercise_handler(ex_type): if ex_type: return agent.run(f"Give me a {ex_type.lower()} practice exercise") return "Please select an exercise type." exercise_btn.click( exercise_handler, inputs=[exercise_type], outputs=[exercise_output] ) with gr.Tab("Free Chat"): with gr.Row(): chat_input = gr.Textbox( label="Ask anything about English", placeholder="e.g., Explain the word great, Give me grammar lesson" ) chat_btn = gr.Button("Ask", variant="primary") chat_output = gr.Markdown() chat_btn.click( agent.run, inputs=[chat_input], outputs=[chat_output] ) # Show welcome message by default demo.load(lambda: agent.run(""), outputs=[chat_output]) return demo # Launch the English Tutor if __name__ == "__main__": demo = create_ui() demo.launch() except ImportError: print("Gradio not available. Running in console mode.") if __name__ == "__main__": print("English Tutor AI - Console Mode") print("=" * 40) print(agent.run("")) while True: try: user_input = input("\nYou: ") if user_input.lower() in ['quit', 'exit', 'bye']: print("Goodbye! Keep practicing your English!") break print("\nTutor:", agent.run(user_input)) except KeyboardInterrupt: print("\nGoodbye! Keep practicing your English!") break