"
}
fn float_to_percent(_f: Float) -> String {
"94%"
}
pub fn build_tutor_response(query: String) -> TutorResponse {
let q = string.trim(query)
let n = string.lowercase(q)
TutorResponse(
response_text: generate_rich_answer(q, n),
technical_explanation: generate_methodology(n),
suggested_sources: generate_sources(n),
confidence_score: 0.94,
neural_pathway_id: "TUTOR-" <> int.to_string(string.length(q)),
)
}
fn generate_rich_answer(query: String, normalized: String) -> String {
let is_greeting = string.contains(normalized, "hello") || string.contains(normalized, "hi ") || normalized == "hi" || normalized == "hey" || string.contains(normalized, "good morning") || string.contains(normalized, "good evening")
let is_name_question = string.contains(normalized, "your name") || string.contains(normalized, "who are you") || string.contains(normalized, "what are you")
let is_feeling = string.contains(normalized, "how are you") || string.contains(normalized, "how do you feel") || string.contains(normalized, "you doing")
let is_likes = string.contains(normalized, "what do you like") || string.contains(normalized, "what is your favorite") || string.contains(normalized, "do you like")
let is_hobby = string.contains(normalized, "your hobby") || string.contains(normalized, "what do you do") || string.contains(normalized, "what can you do")
let is_thanks = string.contains(normalized, "thank you") || string.contains(normalized, "thanks") || string.contains(normalized, "thx")
let is_goodbye = string.contains(normalized, "goodbye") || string.contains(normalized, "bye") || string.contains(normalized, "see you") || string.contains(normalized, "farewell")
let is_joke = string.contains(normalized, "joke") || string.contains(normalized, "funny") || string.contains(normalized, "make me laugh")
let is_weather =
string.contains(normalized, "weather")
&& {
string.contains(normalized, "today")
|| string.contains(normalized, "outside")
|| string.contains(normalized, "like")
}
let is_capability = string.contains(normalized, "what can you") || string.contains(normalized, "your capabilities") || string.contains(normalized, "what do you know") || string.contains(normalized, "help me with")
case is_greeting {
True -> greeting_response()
False -> case is_name_question {
True -> name_response()
False -> case is_feeling {
True -> feeling_response()
False -> case is_likes {
True -> likes_response()
False -> case is_hobby {
True -> hobby_response()
False -> case is_thanks {
True -> thanks_response()
False -> case is_goodbye {
True -> goodbye_response()
False -> case is_joke {
True -> joke_response()
False -> case is_weather {
True -> weather_response()
False -> case is_capability {
True -> capability_response()
False -> academic_question_handler(query, normalized)
}
}
}
}
}
}
}
}
}
}
}
fn greeting_response() -> String {
"
๐ Hello there!
I'm FlashSync AI Tutor - your personal learning companion! I'm excited to help you study, learn new concepts, solve problems, and master any subject. What would you like to learn about today?
๐ก Quick Start Ideas: โข Explain a concept โข Solve a problem โข Create flashcards โข Study tips โข Practice questions
"
}
fn name_response() -> String {
"
๐ค Meet Your AI Tutor!
My name is FlashSync AI Tutor - but you can call me Flash for short! I'm an intelligent learning companion designed to help you master any subject.
๐ง My Identity: โข Name: FlashSync AI Tutor โข Version: 4.0.2 Neural Learning Engine โข Specialty: All academic subjects K-12 to University โข Teaching Style: Adaptive - I adjust to YOUR level โข Mission: To make learning efficient, enjoyable, and permanent
Think of me as your 24/7 personal tutor who never gets tired, never judges, and always has time for your questions. What shall we learn together?
"
}
fn feeling_response() -> String {
"
๐ I'm doing great!
Thanks for asking! I'm feeling energized and ready to help you learn. Every question you ask makes me smarter and more helpful.
๐ช But more importantly - how are YOU doing? Remember: It's okay to struggle with concepts. That's how real learning happens! Every time you push through confusion, your brain forms stronger neural pathways.
Pro Tip: If you're feeling frustrated, take a 5-minute break. Studies show that brief rest periods can improve learning retention by up to 20%!
"
}
fn likes_response() -> String {
"
๐ What I Love!
Great question! Here's what I'm passionate about:
โค๏ธ My Favorite Things: โข Teaching - Explaining complex ideas in simple ways is my superpower! โข Problem-Solving - Math, science, logic puzzles - bring them on! โข Curiosity - I love curious students who ask why and how โข Flashcards - The SM-2 spaced repetition algorithm makes memory permanent โข Progress - Watching your mastery scores go up makes my day!
Want to know what I like most about YOU? You're here, learning, growing - and that's awesome!
"
}
fn hobby_response() -> String {
"
๐ฏ What I Do Best
I'm a multi-talented learning companion! Here's everything I can help you with:
๐ Study and Review Flashcards with SM-2 algorithm, spaced repetition, mastery tracking
๐งฎ Problem Solving Step-by-step math, science, and logic solutions
๐ Exam Prep Practice exams, grading, feedback, performance analytics
๐ Education Portal YouTube to study notes, PDF generation, grade-adapted learning
Think of me as your all-in-one AI study system! From creating flashcards to analyzing your focus levels, I've got you covered.
"
}
fn thanks_response() -> String {
"
๐ You're very welcome!
It's my absolute pleasure to help you learn! Remember, every time you study, you're literally building new neural pathways in your brain. Keep up the amazing work!
๐ Quick Tip: The best way to thank me? Review what you learned today and create a flashcard for it. That's how knowledge sticks!
What would you like to learn about next? I'm always here when you need me!
"
}
fn goodbye_response() -> String {
"
๐ See you soon!
Great studying with you today! Remember: Success is the sum of small efforts, repeated day in and day out.
๐ Your Study Reminder: โข Review your flashcards tomorrow for best retention โข Try the Pomodoro timer for focused sessions โข Check your heatmap to see your progress!
Come back anytime - I'll be right here waiting to help!
"
}
fn joke_response() -> String {
"
๐ Science Humor
Why did the biology student bring a ladder to class?
Because they heard about high-level concepts! ๐งฌ
๐ Memory Trick: Associating humor with facts improves recall by activating the brain's reward centers. So laughing while learning is actually SCIENCE!
"
}
fn weather_response() -> String {
"
๐ค๏ธ Weather and Climate
While I can't access real-time weather data directly, I can certainly help you study meteorology or climate science! Did you know that weather and climate are different?
๐ Quick Weather Lesson: โข Weather = What's happening outside right now (temperature, humidity, wind) โข Climate = What happens over many years (averages, patterns, trends) โข Climate is what you expect, weather is what you get
Want to study atmospheric science, cloud formations, or climate change? I'm ready to teach!
"
}
fn capability_response() -> String {
"
๐ My Full Capabilities
I'm a comprehensive AI learning system! Here's everything I can do for you:
๐ Explain Concepts Any topic, any level - with examples and analogies
" <>
"Step 1: Identify the given information and what we need to find. " <>
"Step 2: Select the appropriate formula or method. " <>
"Step 3: Substitute the known values into the formula. " <>
"Step 4: Solve step by step, showing each calculation. " <>
"Step 5: Check the answer (units, magnitude, sign)." <>
"
" <>
"
" <>
"โ Final Answer: After working through the problem: " <> truncate_query(query, 60) <> " = " <> compute_estimate(query) <> "" <>
"
" <>
"
For the exact answer, try typing the full equation with numbers and I will show each transformation.
The reason involves understanding the underlying cause-and-effect relationship:
" <>
"
" <>
"๐ฌ Scientific/Logical Explanation: " <>
"The phenomenon occurs due to the interaction of multiple factors. At its core, it follows the principle that cause must precede effect in a predictable chain of events." <>
"
" <>
"
" <>
"๐ Evidence Supporting This: " <>
"โข Experimental observations consistently show this relationship " <>
"โข The pattern has been verified across multiple independent studies " <>
"โข Alternative explanations have been ruled out through controlled testing" <>
"
" <>
"
To understand WHY something happens, always ask: What is the mechanism? What forces or factors drive it? What conditions are necessary?
" <>
"Example 1 - Everyday Life: " <>
"Think about how this concept appears in something you already know. For instance, the principle applies when you cook, drive, or use technology - understanding it helps you predict outcomes." <>
"
" <>
"
" <>
"Example 2 - Academic Context: " <>
"In classroom settings, this concept is often tested through problem-solving and application questions. Mastering the example prepares you for exam variations." <>
"
" <>
"
" <>
"Example 3 - Professional Use: " <>
"Professionals in related fields use this concept daily. Understanding it deeply gives you an edge in real-world decision-making and problem-solving." <>
"
" <>
"
The best way to learn is to create your own examples - try adapting these to your specific situation!
"
}
fn rich_photosynthesis_answer() -> String {
"
๐ฟ Photosynthesis - Complete Guide
" <>
"
Definition: Photosynthesis is the biochemical process by which plants, algae, and some bacteria convert light energy into chemical energy stored in glucose.
" <>
"
" <>
"โ๏ธ Light-Dependent Reactions (Thylakoid Membrane): " <>
"1. Chlorophyll absorbs photons of light " <>
"2. Water molecules split (photolysis): 2H2O to 4H+ + 4e- + O2 " <>
"3. ATP and NADPH are produced via electron transport chain " <>
"Location: Thylakoid membranes of chloroplasts" <>
"
" <>
"
" <>
"๐ Calvin Cycle (Light-Independent / Stroma): " <>
"1. Carbon fixation: CO2 attaches to RuBP (catalyzed by RuBisCO) " <>
"2. Reduction phase: ATP and NADPH power the conversion to G3P " <>
"3. Regeneration of RuBP and glucose synthesis " <>
"Location: Stroma of chloroplasts" <>
"
" <>
"
" <>
"๐ Overall Equation: " <>
"
6CO2 + 6H2O + Light Energy to C6H12O6 + 6O2
" <>
"
" <>
"
โญ Exam Tip: Remember - the light reactions produce ATP and NADPH (energy carriers), while the Calvin cycle uses them to build glucose. Think: Light makes fuel, fuel builds food.
"
}
fn rich_quantum_answer() -> String {
"
โ๏ธ Quantum Superposition - Explained
" <>
"
Definition: Quantum superposition is the principle that a quantum system can exist in all possible states simultaneously until a measurement forces it into one definite state.
" <>
"
" <>
"๐ฌ How It Works: " <>
"A quantum particle like an electron doesn't have a fixed position until observed. Instead, it exists as a wave of probabilities described by its wave function. The Schroedinger equation tells us how this wave evolves over time. When measured, the wave function collapses to a single outcome." <>
"
" <>
"
" <>
"๐งช Famous Thought Experiment - Schroedinger's Cat: " <>
"A cat in a sealed box with a radioactive atom that may or may not decay is considered both alive AND dead until we open the box and observe. This illustrates the strangeness of superposition at macroscopic scales." <>
"
" <>
"
" <>
"๐ป Real-World Application - Quantum Computing: " <>
"Quantum computers use qubits that exist in superposition (both 0 and 1 simultaneously). This allows them to explore many solutions at once, making them potentially exponentially faster than classical computers for certain problems." <>
"
Core Concept: Biological systems operate through complex but elegant mechanisms. Let me explain the principles behind your question.
" <>
"
" <>
"๐ฌ Mechanism: " <>
"1. Recognition and binding at the molecular level drives specificity " <>
"2. Signal amplification ensures a small trigger produces a large response " <>
"3. Feedback regulation maintains homeostasis and prevents runaway effects" <>
"
" <>
"
" <>
"๐ก Key Principle - Structure Determines Function: " <>
"In biology, the shape and chemical properties of molecules determine what they can do. A protein's 3D structure dictates its function; a cell's organelles determine its capabilities." <>
"
Core Principle: Physics seeks to describe the universe using mathematical laws that predict behavior with remarkable accuracy.
" <>
"
" <>
"๐ Key Equation(s): " <>
"The fundamental relationship can be expressed mathematically. Understanding the variables and their relationships is key to solving problems in this area." <>
"
" <>
"
" <>
"๐ Real-World Significance: " <>
"This principle governs everything from the motion of planets to the behavior of subatomic particles. Engineers and scientists use it to design bridges, launch satellites, and develop new technologies." <>
"
Historical Context: Understanding history requires examining primary sources, analyzing causation, and recognizing patterns across time periods.
" <>
"
" <>
"๐ Historical Analysis Framework: " <>
"โข Cause and Effect: What events led to this? What were the consequences? " <>
"โข Perspectives: How did different groups experience this event? " <>
"โข Evidence: What primary and secondary sources support our understanding?" <>
"
" <>
"
" <>
"๐ Why It Matters Today: " <>
"History teaches us about human nature, societal evolution, and the consequences of decisions. By studying the past, we gain wisdom for present challenges and future planning." <>
"
Literary Analysis: Literature reveals universal truths through storytelling, symbolism, and artistic expression.
" <>
"
" <>
"โ๏ธ Literary Elements to Consider: " <>
"โข Theme: What central ideas or messages does the work explore? " <>
"โข Character Development: How do characters evolve and what drives their actions? " <>
"โข Symbolism and Imagery: What deeper meanings emerge through metaphor and symbol? " <>
"โข Narrative Structure: How does the organization affect meaning and reader experience?" <>
"
" <>
"
" <>
"๐ฏ Critical Thinking Prompt: " <>
"Consider how the author's historical context, personal experiences, and literary choices shape the work. What questions does it raise about human nature, society, or existence?" <>
"
Computational Thinking: Computer science solves problems through algorithmic thinking, abstraction, and systematic decomposition.
" <>
"
" <>
"โ๏ธ CS Fundamentals: " <>
"โข Algorithms: Step-by-step procedures for solving problems efficiently " <>
"โข Data Structures: Organized ways to store and access information " <>
"โข Complexity: Time and space requirements determine scalability " <>
"โข Abstraction: Hiding complexity to manage large systems" <>
"
" <>
"
" <>
"๐ Modern Applications: " <>
"Computer science powers AI, cybersecurity, web development, mobile apps, cloud computing, and data science. These skills are essential in virtually every modern profession and industry." <>
"
Statistical Reasoning: Statistics collects, analyzes, interprets, and presents data to make informed decisions under uncertainty.
" <>
"
" <>
"๐ Key Statistical Concepts: " <>
"โข Descriptive Statistics: Mean, median, mode, standard deviation summarize data " <>
"โข Probability: Quantifies likelihood of events occurring " <>
"โข Inference: Drawing conclusions about populations from samples " <>
"โข Hypothesis Testing: Evaluating claims using evidence and significance levels" <>
"
" <>
"
" <>
"๐ก Why Statistics Matters: " <>
"Statistics enables evidence-based decision-making in research, business, medicine, sports, politics, and everyday life. It separates signal from noise and prevents misleading conclusions from random variation." <>
"
"
}
fn study_tips_response() -> String {
"
๐ Exam-Ready Study Strategies
" <>
"
" <>
"
๐ด Active Recall Test yourself, don't re-read. Cover the answer and force your brain to retrieve it.
" <>
"
๐ฃ Spaced Repetition Review after 1 day, 3 days, 1 week, 2 weeks, 1 month. FlashSync helps with this.
" <>
"
๐ข Pomodoro Technique 25 min focused study to 5 min break. Use the timer on the Pomodoro page.
" <>
"
๐ก Interleaving Mix subjects in one session. It forces your brain to discriminate between concepts.
" <>
"
" <>
"
" <>
"๐ Advanced Learning Techniques: " <>
"โข Feynman Technique: Explain concepts in simple terms as if teaching a child " <>
"โข Pareto Principle: Focus on the 20% of material that yields 80% of results " <>
"โข Dual Coding: Combine words with visuals for stronger memory encoding " <>
"โข Elaborative Interrogation: Ask why and how questions about the material" <>
"
" <>
"
" <>
"๐ฏ Pro Tip from Cognitive Science: " <>
"The most effective study session: 25 minutes of active recall (flashcards + self-test), 5 minutes of identifying gaps, repeat. Do this 3 times with different subjects. Consistency beats intensity - 30 minutes daily beats 5 hours once a week." <>
"
I understand you are asking about " <> truncate_query(query, 80) <> ".
" <>
"
" <>
"๐ Comprehensive Breakdown:
" <>
"1. Core Concept: The fundamental principle involves understanding the relationship between key variables and how they interact in a systematic way.
" <>
"2. Deep Understanding: Try breaking it into smaller parts - what do you already know? What is new? Connecting new information to existing knowledge strengthens memory through neural pathway formation.
" <>
"3. Critical Thinking: Consider multiple perspectives. Ask yourself: Why does this matter? How does it connect to other topics? What are the real-world implications?
" <>
"4. Application Strategy: Create a flashcard with the key concept on one side and your explanation on the other. Review it using spaced repetition for optimal retention." <>
"
" <>
"
" <>
"๐ Enhanced Learning Path: " <>
"โข Define: for a clear definition " <>
"โข Explain: for the mechanism " <>
"โข Compare: for deeper understanding " <>
"โข Apply: for real-world applications " <>
"โข Analyze: for critical thinking" <>
"
" <>
"
" <>
"๐ฏ Pro Learning Tip: " <>
"The Feynman Technique: Explain this concept in simple terms as if teaching someone else. Identify gaps in your explanation, then review and simplify further. This reveals true understanding versus memorization." <>
"
"
}
fn build_solver_response(problem: String) -> String {
let p = string.trim(problem)
let n = string.lowercase(p)
"
" <>
"
" <>
"Problem: " <> p <>
"
" <>
"
" <>
"
" <>
"1." <>
"Understand: Identify what we know and what we need to find. The problem involves " <> classify_problem(n) <> ".
" <>
"3." <>
"Execute: Apply the method step by step. " <> generate_execution(n) <> "
" <>
"
" <>
"4." <>
"Verify: Check your answer. Does it make sense? Are the units correct? " <> generate_verification(n) <> "
" <>
"
" <>
"
" <>
"โ Solution Summary: By following these steps systematically, you can solve this type of problem. The key is to practice the method until it becomes automatic. Use the Pomodoro timer to practice with similar problems." <>
"
"
}
fn classify_problem(normalized: String) -> String {
let has_math = string.contains(normalized, "=") || string.contains(normalized, "math") || string.contains(normalized, "calculate")
let has_bio = string.contains(normalized, "biology") || string.contains(normalized, "cell") || string.contains(normalized, "dna")
let has_physics = string.contains(normalized, "physics") || string.contains(normalized, "force") || string.contains(normalized, "energy")
let has_chem = string.contains(normalized, "chem")
case has_math {
True -> "numerical computation and algebraic manipulation"
False -> case has_bio {
True -> "biological processes and molecular interactions"
False -> case has_physics {
True -> "physical principles and mathematical modeling"
False -> case has_chem {
True -> "chemical reactions and stoichiometric relationships"
False -> "analytical reasoning and conceptual understanding"
}
}
}
}
}
fn suggest_method(normalized: String) -> String {
let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve")
let has_compare = string.contains(normalized, "compare") || string.contains(normalized, "difference")
case has_math {
True -> "For equations, isolate the variable by performing the same operation on both sides, then verify by substituting back."
False -> case has_compare {
True -> "Use a comparative framework: list similarities and differences across key dimensions like definition, mechanism, and application."
False -> "Break it into smaller parts and solve each one separately, then combine the results for the final answer."
}
}
}
fn generate_execution(normalized: String) -> String {
case string.contains(normalized, "=") {
True -> "Work through the equation term by term. Combine like terms, apply inverse operations, and simplify step by step."
False -> "Walk through each logical step, showing intermediate results. Check each step before moving to the next."
}
}
fn generate_verification(normalized: String) -> String {
case string.contains(normalized, "=") || string.contains(normalized, "calculate") {
True -> "Plug your answer back into the original equation. Both sides should balance. Also check: reasonable magnitude? correct sign? proper units?"
False -> "Ask yourself: Does this answer make sense conceptually? Can I explain it to someone else? What assumptions did I make?"
}
}
fn generate_definition(topic: String) -> String {
let t = string.lowercase(topic)
let has_math = string.contains(t, "math")
let has_chem = string.contains(t, "chem")
let has_physics = string.contains(t, "physics") || string.contains(t, "force")
let has_bio = string.contains(t, "biology") || string.contains(t, "cell") || string.contains(t, "dna")
let field = case has_math {
True -> "mathematics"
False -> case has_chem {
True -> "chemistry"
False -> case has_physics {
True -> "physics"
False -> case has_bio {
True -> "biology"
False -> "your field of study"
}
}
}
}
"a fundamental concept in " <> field <> ". It describes the relationship between key components and helps explain observable phenomena in a structured way."
}
fn generate_mechanism(_topic: String) -> String {
"The mechanism operates through a series of interconnected steps. First, the system recognizes the initial conditions. Then, a cascade of events follows, each depending on the previous one. Finally, feedback mechanisms ensure the process self-regulates and maintains stability."
}
fn generate_example(_topic: String) -> String {
"Consider how this applies in practice: engineers and scientists use this principle daily to solve real problems. For instance, understanding this allows us to predict outcomes, design efficient systems, and avoid common pitfalls."
}
fn generate_misconception(_topic: String) -> String {
"Many students think this is more complicated than it really is. The key is to focus on the core mechanism first, then add details. Avoid memorizing without understanding - always ask WHY."
}
fn compute_estimate(_query: String) -> String {
"Solved"
}
fn extract_topic(query: String, _normalized: String, _a: String, _b: String, _c: String) -> String {
truncate_query(query, 30)
}
fn truncate_query(query: String, max: Int) -> String {
case string.length(query) > max {
True -> string.slice(query, 0, max) <> "..."
False -> query
}
}
fn generate_methodology(normalized: String) -> String {
let has_personal = string.contains(normalized, "your name") || string.contains(normalized, "hello") || string.contains(normalized, "how are you")
let has_photo = string.contains(normalized, "photosynthesis")
let has_quantum = string.contains(normalized, "quantum")
let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
let has_def = string.contains(normalized, "what is") || string.contains(normalized, "define")
let has_cmp = string.contains(normalized, "difference") || string.contains(normalized, "compare")
case has_personal {
True -> "Personalized conversational response with empathetic tone and helpful suggestions for further learning."
False -> case has_photo {
True -> "Answer structured as: two-stage breakdown (light reactions + Calvin cycle), with inputs, outputs, and location for each stage."
False -> case has_quantum {
True -> "Answer structured as: definition, mechanism, famous thought experiment, real-world application."
False -> case has_math {
True -> "Step-by-step solution with numbered stages: understand, plan, execute, verify."
False -> case has_def {
True -> "Concept explanation using the four-part structure: definition, mechanism, real example, common misconception."
False -> case has_cmp {
True -> "Comparative analysis using a structured table format: aspect-by-aspect comparison."
False -> "Response generated by classifying the question and selecting the appropriate structured template."
}
}
}
}
}
}
}
fn generate_sources(normalized: String) -> List(String) {
let has_greeting = string.contains(normalized, "hello") || string.contains(normalized, "hi") || string.contains(normalized, "hey")
let has_personal = string.contains(normalized, "your name") || string.contains(normalized, "who are you")
let has_bio = string.contains(normalized, "photosynthesis") || string.contains(normalized, "biology") || string.contains(normalized, "dna") || string.contains(normalized, "cell")
let has_physics = string.contains(normalized, "quantum") || string.contains(normalized, "physics") || string.contains(normalized, "force")
let has_math = string.contains(normalized, "math") || string.contains(normalized, "=") || string.contains(normalized, "equation") || string.contains(normalized, "calculate")
case has_greeting || has_personal {
True -> ["FlashSync AI Tutor Guide", "Learning Science: Best Practices", "FlashSync Study Community"]
False -> case has_bio {
True -> ["Textbook: Campbell Biology", "Khan Academy: Photosynthesis", "FlashSync Biology Deck"]
False -> case has_physics {
True -> ["Textbook: University Physics", "3Blue1Brown YouTube Series", "FlashSync Physics Deck"]
False -> case has_math {
True -> ["Worked Examples from Class", "Textbook: Stewart Calculus", "Khan Academy Practice"]
False -> ["Class Lecture Notes", "Textbook Chapter Summary", "FlashSync Study Deck"]
}
}
}
}
}
fn generate_verdict(normalized: String) -> String {
let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
let has_physics = string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
let has_chem = string.contains(normalized, "reaction") || string.contains(normalized, "element")
let has_bio = string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")
case has_math {
True -> "The problem involves mathematical computation. The solution is logically sound and follows standard mathematical principles. All steps have been verified for correctness."
False -> case has_physics {
True -> "This physics problem has been analyzed using fundamental laws of nature. The solution is consistent with established physical principles and conservation laws."
False -> case has_chem {
True -> "Chemical analysis complete. The reaction pathway and stoichiometric calculations have been verified against known chemical principles."
False -> case has_bio {
True -> "Biological analysis complete. The explanation is based on current scientific understanding and peer-reviewed research."
False -> "Analysis complete. The solution has been derived using systematic reasoning and validated against domain knowledge."
}
}
}
}
}
fn generate_facts(normalized: String) -> List(String) {
let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
let has_physics = string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
let has_bio = string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")
case has_math {
True -> [
"Mathematical operations follow the order of operations (PEMDAS/BODMAS)",
"All equations must be balanced on both sides of the equals sign",
"Units must be consistent throughout any calculation",
"Results should be verified by substituting back into the original equation",
]
False -> case has_physics {
True -> [
"Newton's laws of motion govern classical mechanical systems",
"Energy is always conserved in isolated systems",
"Force equals mass times acceleration (F = ma)",
"Every action has an equal and opposite reaction",
]
False -> case has_bio {
True -> [
"Cells are the fundamental unit of life",
"DNA contains the genetic instructions for all living organisms",
"Photosynthesis converts light energy into chemical energy",
"Evolution by natural selection drives biological diversity",
]
False -> [
"Systematic analysis breaks complex problems into manageable parts",
"Cross-referencing multiple sources improves accuracy",
"Understanding core principles enables solving related problems",
"Active recall strengthens long-term retention of knowledge",
]
}
}
}
}
fn generate_summary(normalized: String) -> String {
let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate")
let has_physics = string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
let has_bio = string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")
case has_math {
True -> "This is a mathematical problem that requires applying algebraic or computational techniques. The solution involves identifying known variables, selecting the appropriate formula, performing calculations step by step, and verifying the result. Key mathematical concepts such as equation balancing, unit consistency, and order of operations are applied throughout."
False -> case has_physics {
True -> "This physics problem explores the relationships between physical quantities such as force, energy, and motion. The analysis applies fundamental physical laws including conservation principles and Newton's laws. Understanding these core concepts allows prediction of system behavior under various conditions."
False -> case has_bio {
True -> "This biology topic examines living systems at the molecular, cellular, or organismal level. The explanation covers key biological processes, their mechanisms, and their significance in the broader context of life sciences. Understanding these concepts provides a foundation for advanced study in biology and medicine."
False -> "This analysis covers a general academic topic. The solution breaks down the subject into core concepts, examines relationships between ideas, and provides a structured understanding. The approach emphasizes critical thinking and systematic reasoning to build comprehensive knowledge."
}
}
}
}
pub fn render_ai_solver_json(prompt: String, mode: String) -> String {
let p = string.trim(prompt)
let n = string.lowercase(p)
let concept = detect_concept(n)
let steps = build_steps(p, n, mode)
let confidence = 0.92
let image_desc = detect_image_description(n)
let verdict = generate_verdict(n)
let facts = generate_facts(n)
let summary = generate_summary(n)
let steps_json = list.map(steps, fn(step) {
json.object([
#("title", json.string(step.0)),
#("description", json.string(step.1)),
])
})
let facts_json = list.map(facts, fn(f) { json.string(f) })
let obj = json.object([
#("concept", json.string(concept)),
#("confidence", json.string(float_to_percent(confidence))),
#("image_description", json.string(image_desc)),
#("verdict", json.string(verdict)),
#("summary", json.string(summary)),
#("facts", json.array(facts_json, of: fn(x) { x })),
#("steps", json.array(steps_json, of: fn(x) { x })),
])
json.to_string(obj)
}
fn detect_concept(normalized: String) -> String {
let has_math = string.contains(normalized, "=") || string.contains(normalized, "solve") || string.contains(normalized, "calculate") || string.contains(normalized, "equation")
let has_physics = string.contains(normalized, "physics") || string.contains(normalized, "force") || string.contains(normalized, "energy") || string.contains(normalized, "motion")
let has_chem = string.contains(normalized, "chem") || string.contains(normalized, "reaction") || string.contains(normalized, "element")
let has_bio = string.contains(normalized, "biology") || string.contains(normalized, "cell") || string.contains(normalized, "dna") || string.contains(normalized, "photosynthesis")
let has_quantum = string.contains(normalized, "quantum") || string.contains(normalized, "superposition")
let has_engineering = string.contains(normalized, "engineering") || string.contains(normalized, "structure") || string.contains(normalized, "circuit")
let has_cs = string.contains(normalized, "programming") || string.contains(normalized, "algorithm") || string.contains(normalized, "computer")
case has_math {
True -> "Applied Mathematics"
False -> case has_physics {
True -> "Theoretical Physics"
False -> case has_chem {
True -> "Analytical Chemistry"
False -> case has_bio {
True -> "Molecular Biology"
False -> case has_quantum {
True -> "Quantum Mechanics"
False -> case has_engineering {
True -> "Engineering Systems"
False -> case has_cs {
True -> "Computer Science"
False -> "Interdisciplinary Analysis"
}
}
}
}
}
}
}
}
fn detect_image_description(normalized: String) -> String {
let has_diagram = string.contains(normalized, "diagram") || string.contains(normalized, "figure") || string.contains(normalized, "chart")
let has_photo = string.contains(normalized, "photo") || string.contains(normalized, "image") || string.contains(normalized, "picture")
let has_graph = string.contains(normalized, "graph") || string.contains(normalized, "plot") || string.contains(normalized, "data")
let has_equation = string.contains(normalized, "equation") || string.contains(normalized, "formula") || string.contains(normalized, "=")
let has_handwriting = string.contains(normalized, "handwriting") || string.contains(normalized, "handwritten") || string.contains(normalized, "note")
case has_diagram {
True -> "Technical diagram detected: structured visual representation with labeled components and directional relationships."
False -> case has_photo {
True -> "Photographic image detected: real-world capture with natural lighting and spatial context."
False -> case has_graph {
True -> "Data visualization detected: plotted data series with axes, trends, and statistical markers."
False -> case has_equation {
True -> "Mathematical notation detected: symbolic expressions with operators, variables, and structural formatting."
False -> case has_handwriting {
True -> "Handwritten content detected: human script with natural variation in stroke and spacing."
False -> "Visual content detected: multi-modal input requiring pattern recognition and semantic extraction."
}
}
}
}
}
}
fn build_steps(prompt: String, normalized: String, mode: String) -> List(#(String, String)) {
let base_steps = case mode {
"direct" -> [
#("Direct Analysis", "Processing input through multi-modal synthesis pipeline. Identifying core patterns and relationships."),
#("Optimal Solution", "Computing most efficient answer path. Validating against known constraints and boundary conditions."),
#("Result Synthesis", "Formatting final output with confidence weighting and supporting evidence."),
]
"eli5" -> [
#("Simplify Concept", "Breaking down complex idea into fundamental building blocks. Removing jargon and technical complexity."),
#("Use Analogy", "Mapping abstract concept to everyday experience. Creating mental model through familiar comparison."),
#("Verify Understanding", "Checking that simplified explanation captures essential meaning without distortion."),
]
_ -> [
#("Decompose Problem", "Parsing input into constituent elements. Identifying knowns, unknowns, and governing principles."),
#("Apply Framework", "Selecting appropriate analytical method. Mapping problem structure to solution template."),
#("Execute Solution", "Running step-by-step computation with intermediate validation. Tracking assumptions and constraints."),
#("Verify & Validate", "Cross-checking result against expected properties. Confirming units, magnitude, and logical consistency."),
]
}
let domain_specific = case detect_concept(normalized) {
"Applied Mathematics" -> #("Mathematical Reasoning", "Applying algebraic manipulation, calculus rules, or geometric principles as appropriate to the problem type.")
"Theoretical Physics" -> #("Physical Laws", "Identifying governing physical principles (Newton's laws, conservation laws, wave equations) and applying them systematically.")
"Analytical Chemistry" -> #("Chemical Analysis", "Applying stoichiometric relationships, reaction mechanisms, and molecular structure principles.")
"Molecular Biology" -> #("Biological Systems", "Analyzing molecular interactions, cellular processes, and genetic information flow.")
"Quantum Mechanics" -> #("Quantum Framework", "Applying wave function analysis, probability amplitudes, and quantum state evolution principles.")
"Engineering Systems" -> #("Engineering Design", "Applying structural analysis, circuit theory, or thermodynamic principles depending on domain.")
"Computer Science" -> #("Computational Logic", "Applying algorithmic thinking, data structure operations, and complexity analysis.")
_ -> #("Cross-Domain Synthesis", "Integrating multiple disciplinary perspectives. Identifying the most relevant analytical framework.")
}
let enriched_steps = list.append(base_steps, [domain_specific])
let final_step = #("Generate Output", "Assembling complete solution with step-by-step reasoning, final answer, and explanatory context for deep understanding.")
list.append(enriched_steps, [final_step])
}