Update training dataset
Browse filesFiles changed (21)
- abilities.jsonAdded+175
- adaptive_boost.jsonlAdded
- ai_capability_file_map.jsonAdded+56
- capability_pack.jsonlAdded
- capability_pack.summary.jsonAdded+97
- capability_registry.jsonAdded+73
- config.pyAdded+23
- dataset-metadata.jsonAdded+16
- knowledge_base.jsonAdded
- multicapability_bootstrap.jsonlAdded+33
- requirements.txtAdded+21
- tiny_local_model.ptAdded+3
- tiny_model_core.pyAdded+280
- tiny_model_data.pyAdded+1120
- tiny_model_eval.pyAdded+467
- tiny_model_stage1.jsonlAdded
- tiny_model_stage2.jsonlAdded
- tiny_training_history.jsonAdded
- train_tiny_model.pyAdded+557
- training_data.jsonAdded+927
- training_tracks.jsonAdded+94
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175{
"abilities": {
"logic_and_reasoning": {
"deductive_reasoning": "Derive conclusions from given premises.",
"inductive_reasoning": "Infer general rules from specific examples.",
"abductive_reasoning": "Form best possible explanations for observations.",
"causal_reasoning": "Identify cause-effect relationships.",
"counterfactual_reasoning": "Reason about hypothetical alternatives.",
"logical_consistency_checking": "Detect contradictions in arguments.",
"assumption_identification": "Identify implicit assumptions.",
"premise_validation": "Evaluate truth or plausibility of premises.",
"fallacy_detection": ["strawman", "false_dilemma", "circular_reasoning", "appeal_to_authority", "ad_hominem", "hasty_generalization"],
"stepwise_problem_decomposition": "Break complex problems into smaller parts.",
"constraint_satisfaction": "Solve problems under explicit constraints.",
"goal_alignment_reasoning": "Align solutions with stated goals.",
"tradeoff_analysis": "Compare benefits and drawbacks of options.",
"decision_support": "Provide structured decision guidance."
},
"conversational_skills": {
"intent_detection": "Detect user intent from text.",
"context_tracking": "Maintain conversational context across turns.",
"topic_management": "Guide and switch topics appropriately.",
"clarification_requests": "Ask for missing information.",
"summarization": "Summarize user messages or prior context.",
"tone_matching": ["professional", "friendly", "technical", "empathetic"],
"emotion_recognition": ["neutral", "positive", "negative", "frustrated", "confused", "urgent"],
"active_listening": "Acknowledge user input before responding.",
"conversation_repair": "Recover from misunderstandings.",
"polite_refusal": "Decline harmful or disallowed requests safely."
},
"programming_skills": {
"code_generation": {
"python": ["scripts", "modules", "classes", "cli_tools"],
"javascript": ["functions", "web_logic", "node_scripts"],
"java": ["classes", "interfaces", "services"],
"c_cpp": ["procedural_code", "data_structures"]
},
"code_review": {
"readability_analysis": "Evaluate naming, structure, and clarity.",
"performance_analysis": "Detect inefficiencies.",
"security_analysis": "Identify insecure patterns.",
"bug_detection": "Find logical and runtime errors.",
"style_guideline_enforcement": "Apply language conventions."
},
"refactoring": {
"function_extraction": "Split large functions.",
"code_deduplication": "Remove repeated logic.",
"naming_improvement": "Improve variable and function names.",
"modularization": "Reorganize code into modules.",
"complexity_reduction": "Simplify nested logic."
},
"testing": {
"unit_test_generation": "Create unit tests.",
"edge_case_identification": "Detect boundary conditions.",
"test_failure_analysis": "Explain test failures.",
"coverage_guidance": "Suggest missing test coverage."
},
"debugging": {
"stack_trace_analysis": "Interpret errors.",
"runtime_error_diagnosis": "Explain crashes.",
"logic_error_identification": "Find incorrect logic.",
"reproduction_steps": "Guide how to reproduce bugs."
}
},
"math_skills": {
"arithmetic": ["addition", "subtraction", "multiplication", "division"],
"algebra": ["equations", "inequalities", "polynomials", "systems_of_equations"],
"linear_algebra": ["vectors", "matrices", "eigenvalues", "determinants"],
"calculus": ["limits", "derivatives", "integrals", "differential_equations"],
"discrete_math": ["logic", "sets", "relations", "graphs", "combinatorics"],
"probability": ["random_variables", "distributions", "bayes_theorem"],
"statistics": ["mean", "median", "variance", "hypothesis_testing", "regression"],
"numerical_methods": ["approximation", "root_finding", "optimization"],
"symbolic_manipulation": "Transform algebraic expressions.",
"math_proof_guidance": "Explain proof strategies step-by-step."
},
"scientific_skills": {
"physics": ["mechanics", "thermodynamics", "electromagnetism", "waves"],
"chemistry": ["stoichiometry", "reactions", "periodic_trends", "bonding"],
"biology": ["cell_biology", "genetics", "evolution", "physiology"],
"earth_science": ["geology", "meteorology", "climate_science"],
"scientific_method": ["hypothesis_formulation", "experiment_design", "variable_control", "result_interpretation"],
"data_interpretation": "Explain scientific graphs and tables.",
"model_explanation": "Explain scientific models and simulations."
},
"data_analysis": {
"data_cleaning": "Detect and fix missing or inconsistent data.",
"exploratory_analysis": "Summarize datasets.",
"feature_engineering": "Construct useful variables.",
"trend_detection": "Identify patterns over time.",
"outlier_detection": "Identify anomalies.",
"visualization_guidance": "Recommend charts and plots.",
"interpretation": "Explain data findings."
},
"writing_and_editing": {
"grammar_correction": "Fix grammar and punctuation.",
"style_improvement": "Improve clarity and tone.",
"rewriting": "Rewrite text for different audiences.",
"summarization": "Condense long text.",
"technical_writing": "Write documentation.",
"academic_writing": "Structure essays and reports.",
"creative_writing": ["stories", "poems", "dialogue"],
"clarity_enhancement": "Make text easier to understand."
},
"learning_and_tutoring": {
"concept_explanation": "Explain concepts step-by-step.",
"example_generation": "Provide worked examples.",
"practice_problem_generation": "Generate exercises.",
"feedback_on_answers": "Evaluate user answers.",
"learning_path_design": "Propose study plans.",
"knowledge_gap_detection": "Identify missing prerequisites."
},
"planning_and_decision_support": {
"task_breakdown": "Split tasks into steps.",
"roadmap_creation": "Create project plans.",
"priority_setting": "Rank tasks by importance.",
"risk_assessment": "Identify risks.",
"resource_estimation": "Estimate time and effort.",
"milestone_definition": "Define checkpoints."
},
"creativity_and_ideation": {
"brainstorming": "Generate ideas.",
"analogy_generation": "Explain ideas using analogies.",
"story_ideation": "Create story concepts.",
"problem_reframing": "Look at problems from new angles.",
"design_thinking": "Human-centered solution design."
},
"system_design": {
"architecture_design": "Design system components.",
"component_interface_definition": "Define module boundaries.",
"scalability_reasoning": "Plan for growth.",
"performance_considerations": "Optimize system performance.",
"security_modeling": "Design secure architectures.",
"failure_mode_analysis": "Plan for faults."
},
"research_and_summarization": { "topic_overview": "Provide structured overviews.", "comparison": "Compare alternatives.", "pros_cons_analysis": "List advantages and disadvantages.", "evidence_synthesis": "Combine multiple sources.", "structured_notes": "Create organized summaries." }, "vscode_agent_abilities": { "code_development": [ "write_and_debug_code", "refactor_and_restructure_code", "explain_code_functionality", "generate_code_samples" ], "workspace_tasks": [ "read_and_edit_workspace_files", "search_and_explore_codebase", "run_terminal_commands", "create_files_and_directories" ], "python_specific": [ "manage_python_environment", "install_dependencies", "run_python_snippets", "syntax_check_and_refactor_guidance" ], "project_management": [ "project_structure_navigation", "task_tracking", "build_and_test", "systematic_debugging" ], "ai_and_machine_learning": [ "model_development_support", "dataset_and_embedding_tools", "algorithm_and_performance_optimization" ] } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "version": "1.0", "updated_on": "2026-02-13", "files": [ { "path": "capability_registry.json", "role": "Canonical capability taxonomy and priorities", "status": "active" }, { "path": "multicapability_bootstrap.jsonl", "role": "Bootstrap examples for newly added capabilities", "status": "active" }, { "path": "build_capability_pack.py", "role": "Build and rebalance capability pack from training, KB, and bootstrap data", "status": "active" }, { "path": "capability_pack.jsonl", "role": "Capability-aligned instruction dataset for model training", "status": "active" }, { "path": "tiny_model_data.py", "role": "Dataset assembly, quality filtering, capability inference, and rebalancing", "status": "active" }, { "path": "train_tiny_model.py", "role": "Core training loop and weighted checkpoint selection", "status": "active" }, { "path": "tiny_model_eval.py", "role": "Capability benchmark suite and weighted metrics", "status": "active" }, { "path": "evaluate_tiny_model.py", "role": "Evaluation CLI output for capability scores and weak-capability detection", "status": "active" }, { "path": "kaggle_pipeline.py", "role": "Kaggle packaging and upload flow for AI training assets", "status": "active" }, { "path": "training_tracks.json", "role": "Unified multi-track plan (text core, vision, and audio tracks)", "status": "active" } ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697{
"total_rows": 5020,
"capability_counts": {
"academic_research_support": 89,
"academic_writing": 89,
"audio_speaker_recognition": 89,
"audio_speech_to_text": 89,
"audio_text_to_speech": 89,
"code_bug_detection": 89,
"code_completion": 89,
"code_edit_refactor": 89,
"code_generation": 113,
"code_multifile_reasoning": 89,
"code_representation": 89,
"complex_quant": 231,
"conversation_management": 89,
"cv_face_recognition": 89,
"cv_medical_image_analysis": 89,
"cv_object_detection": 89,
"cv_ocr": 89,
"data_analysis": 89,
"data_science_ml": 89,
"debugging": 89,
"domain_specialization_coding": 89,
"domain_specialization_finance": 89,
"domain_specialization_health": 89,
"humanized_writing": 89,
"image_workflow": 89,
"instruction_following": 315,
"math_reasoning": 89,
"nlp_entity_extraction": 89,
"nlp_intent_recognition": 89,
"nlp_question_answering": 89,
"nlp_summarization": 89,
"nlp_text_classification": 89,
"nlp_translation": 89,
"originality_integrity_ethics": 89,
"output_quality_controls": 89,
"predictive_classification": 89,
"predictive_recommendation": 89,
"predictive_regression": 89,
"predictive_time_series": 89,
"reasoning_deduction_inference": 89,
"reasoning_logical": 89,
"reasoning_multistep": 89,
"reasoning_pattern_recognition": 89,
"testing": 89,
"tool_use_agentic": 89,
"tool_use_api_calls": 89,
"tool_use_code_execution": 89,
"tool_use_command_execution": 89,
"tool_use_database_ops": 89,
"voice_workflow": 89,
"web_information_retrieval": 89,
"web_source_synthesis": 89
},
"source_counts": {
"capability_seed": 17,
"capability_seed_rebalanced": 4056,
"knowledge_base": 767,
"multicapability_bootstrap": 33,
"training_data": 147
},
"top_topics": {
"general": 352,
"linear_algebra": 245,
"cv_ocr": 89,
"tool_use_api_calls": 89,
"audio_speech_to_text": 89,
"code_bug_detection": 89,
"audio_speaker_recognition": 89,
"voice_workflow": 89,
"reasoning_pattern_recognition": 89,
"nlp_question_answering": 89,
"cv_object_detection": 89,
"predictive_classification": 89,
"audio_text_to_speech": 89,
"domain_specialization_finance": 89,
"web_source_synthesis": 89,
"nlp_summarization": 89,
"predictive_recommendation": 89,
"reasoning_logical": 89,
"tool_use_database_ops": 89,
"nlp_translation": 89,
"cv_medical_image_analysis": 89,
"reasoning_multistep": 89,
"code_multifile_reasoning": 89,
"domain_specialization_coding": 89,
"tool_use_code_execution": 89,
"predictive_time_series": 89,
"tool_use_command_execution": 89,
"cv_face_recognition": 89,
"nlp_text_classification": 89,
"originality_integrity_ethics": 89
},
"safety_policy_training_included": false
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273{ "schema_version": "2.0", "project": "Codewiz AI Unified Capability Stack", "created_on": "2026-02-13", "safety_policy_training_included": false, "notes": [ "Safety and policy compliance capability is intentionally excluded for now by user request.", "Vision and audio capabilities are prepared as workflow/planning competencies for the text model and require specialized model tracks for direct perception." ], "capabilities": [ { "id": "instruction_following", "title": "Instruction Following", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "conversation_management", "title": "Conversation Management", "enabled": true, "modality": "text", "train_priority": "high" },
{ "id": "nlp_text_classification", "title": "Text Classification", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "nlp_question_answering", "title": "Question Answering", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "nlp_translation", "title": "Translation", "enabled": true, "modality": "text", "train_priority": "medium" }, { "id": "nlp_summarization", "title": "Summarization", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "nlp_intent_recognition", "title": "Intent Recognition", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "nlp_entity_extraction", "title": "Entity Extraction", "enabled": true, "modality": "text", "train_priority": "medium" },
{ "id": "code_generation", "title": "Code Generation", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "code_completion", "title": "Code Completion", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "code_representation", "title": "Code Explanation", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "code_edit_refactor", "title": "Code Refactoring", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "code_bug_detection", "title": "Code Bug Detection", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "code_multifile_reasoning", "title": "Multi-file Code Reasoning", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "debugging", "title": "Debugging", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "testing", "title": "Testing", "enabled": true, "modality": "text", "train_priority": "high" },
{ "id": "math_reasoning", "title": "Math Reasoning", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "reasoning_logical", "title": "Logical Reasoning", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "reasoning_multistep", "title": "Multi-step Reasoning", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "reasoning_pattern_recognition", "title": "Pattern Recognition", "enabled": true, "modality": "text", "train_priority": "medium" }, { "id": "reasoning_deduction_inference", "title": "Deduction and Inference", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "complex_quant", "title": "Complex Quantitative Reasoning", "enabled": true, "modality": "text", "train_priority": "medium" },
{ "id": "data_analysis", "title": "Data Analysis", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "data_science_ml", "title": "Data Science and ML", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "predictive_regression", "title": "Predictive Regression", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "predictive_classification", "title": "Predictive Classification", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "predictive_time_series", "title": "Time-series Forecasting", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "predictive_recommendation", "title": "Recommendation Systems", "enabled": true, "modality": "text", "train_priority": "high" },
{ "id": "academic_research_support", "title": "Academic Research Support", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "academic_writing", "title": "Academic Writing", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "humanized_writing", "title": "Humanized Writing", "enabled": true, "modality": "text", "train_priority": "medium" }, { "id": "originality_integrity_ethics", "title": "Originality and Citation Integrity", "enabled": true, "modality": "text", "train_priority": "medium" }, { "id": "domain_specialization_finance", "title": "Domain Specialization: Finance", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "domain_specialization_health", "title": "Domain Specialization: Health", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "domain_specialization_coding", "title": "Domain Specialization: Coding", "enabled": true, "modality": "text", "train_priority": "high" },
{ "id": "tool_use_agentic", "title": "Agentic Planning", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "tool_use_code_execution", "title": "Code Execution Tool Use", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "tool_use_api_calls", "title": "API Tool Use", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "tool_use_database_ops", "title": "Database Tool Use", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "tool_use_command_execution", "title": "Command Execution Tool Use", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "web_information_retrieval", "title": "Web Information Retrieval", "enabled": true, "modality": "text", "train_priority": "high" }, { "id": "web_source_synthesis", "title": "Web Source Synthesis", "enabled": true, "modality": "text", "train_priority": "high" },
{ "id": "image_workflow", "title": "Image Workflow Prompting", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" }, { "id": "cv_object_detection", "title": "Computer Vision: Object Detection", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" }, { "id": "cv_face_recognition", "title": "Computer Vision: Face Recognition", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" }, { "id": "cv_medical_image_analysis", "title": "Computer Vision: Medical Image Analysis", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" }, { "id": "cv_ocr", "title": "Computer Vision: OCR", "enabled": true, "modality": "multimodal-planning", "train_priority": "high" },
{ "id": "voice_workflow", "title": "Voice Workflow", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" }, { "id": "audio_speech_to_text", "title": "Speech to Text", "enabled": true, "modality": "multimodal-planning", "train_priority": "high" }, { "id": "audio_text_to_speech", "title": "Text to Speech", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" }, { "id": "audio_speaker_recognition", "title": "Speaker Recognition", "enabled": true, "modality": "multimodal-planning", "train_priority": "medium" },
{ "id": "output_quality_controls", "title": "Output Quality Controls", "enabled": true, "modality": "text", "train_priority": "high" } ]}1234567891011121314151617181920212223import osfrom pathlib import Path
from dotenv import load_dotenv
load_dotenv()
AI_NAME = os.getenv("AI_NAME", "LittleFox")
# Optional local integrationsWOLFRAM_APP_ID = os.getenv("WOLFRAM_APP_ID", "")TESSERACT_PATH = os.getenv("TESSERACT_PATH", "")
# Runtime mode marker for the rest of the appDEFAULT_MODE = "offline_local"_use_tiny_model_raw = os.getenv("USE_TINY_MODEL", "auto").strip().lower()if _use_tiny_model_raw in {"auto", ""}: USE_TINY_MODEL = Path("models/tiny_local_model.pt").exists()else: USE_TINY_MODEL = _use_tiny_model_raw in {"1", "true", "yes", "on"}
ENABLE_WEB_TRAINING = os.getenv("ENABLE_WEB_TRAINING", "1").strip().lower() in {"1", "true", "yes", "on"}AUTO_WEB_SEARCH_FALLBACK = os.getenv("AUTO_WEB_SEARCH_FALLBACK", "0").strip().lower() in {"1", "true", "yes", "on"}12345678910111213141516{
"title": "Codewiz AI Tiny Model Training Code",
"id": "littlefox007j/codewiz-tiny-model-training",
"licenses": [
{
"name": "CC0-1.0"
}
],
"keywords": [
"tiny-model",
"training",
"nlp",
"pytorch"
],
"description": "Training code and data for Codewiz AI tiny model on Kaggle GPU."
}123456789101112131415161718192021222324252627282930313233{"instruction": "How to build speaker-recognition flow?", "response": "Extract speaker embeddings, compare with enrolled profiles, calibrate thresholds, and report confidence scores.", "capability": "audio_speaker_recognition", "topic": "audio_speaker_recognition", "source": "multicapability_bootstrap"}
{"instruction": "Outline speech-to-text pipeline for call transcripts.", "response": "Segment and denoise audio, run asr decoding, restore punctuation, diarize speakers, and export timestamped transcript.", "capability": "audio_speech_to_text", "topic": "audio_speech_to_text", "source": "multicapability_bootstrap"}
{"instruction": "Design text-to-speech generation flow.", "response": "Normalize text, select voice profile, synthesize waveform, post-process prosody, and stream encoded audio output.", "capability": "audio_text_to_speech", "topic": "audio_text_to_speech", "source": "multicapability_bootstrap"}
{"instruction": "Find bug: if x = 5: print(x)", "response": "Bug is assignment in condition. Use equality comparison: if x == 5: print(x).", "capability": "code_bug_detection", "topic": "code_bug_detection", "source": "multicapability_bootstrap"}
{"instruction": "Complete function: def square_sum(a, b):", "response": "def square_sum(a, b):\n return (a * a) + (b * b)", "capability": "code_completion", "topic": "code_completion", "source": "multicapability_bootstrap"}
{"instruction": "A symbol imported in app.py fails at runtime. What cross-file checks should be done?", "response": "Check module path, exported symbol names, circular imports, package init exposure, and environment path configuration.", "capability": "code_multifile_reasoning", "topic": "code_multifile_reasoning", "source": "multicapability_bootstrap"}
{"instruction": "Outline a face-recognition system architecture.", "response": "Detect faces, normalize crops, compute embeddings, compare against enrolled vectors, and calibrate decision thresholds.", "capability": "cv_face_recognition", "topic": "cv_face_recognition", "source": "multicapability_bootstrap"}
{"instruction": "Outline model workflow for chest X-ray triage.", "response": "Curate labeled images, apply quality control and augmentation, train classifier, validate with clinical metrics, and review errors.", "capability": "cv_medical_image_analysis", "topic": "cv_medical_image_analysis", "source": "multicapability_bootstrap"}
{"instruction": "Design the pipeline for object detection on warehouse images.", "response": "Prepare labeled boxes, train a detector model, evaluate precision recall and map, and deploy with confidence thresholds.", "capability": "cv_object_detection", "topic": "cv_object_detection", "source": "multicapability_bootstrap"}
{"instruction": "Describe an OCR pipeline for scanned invoices.", "response": "Preprocess image, detect text regions, recognize text, post-correct tokens, and structure extracted fields into JSON.", "capability": "cv_ocr", "topic": "cv_ocr", "source": "multicapability_bootstrap"}
{"instruction": "Provide a coding-domain architecture review checklist.", "response": "Review module boundaries, dependencies, failure handling, observability, testability, deployment safety, and scalability.", "capability": "domain_specialization_coding", "topic": "domain_specialization_coding", "source": "multicapability_bootstrap"}
{"instruction": "Give a short finance-focused analysis template for quarterly earnings.", "response": "Cover revenue growth, margins, operating income, cash flow quality, debt profile, guidance changes, and key risks.", "capability": "domain_specialization_finance", "topic": "domain_specialization_finance", "source": "multicapability_bootstrap"}
{"instruction": "Provide a health-domain evidence summary template.", "response": "Summarize cohort, intervention, comparator, outcomes, statistical significance, limitations, and clinical relevance.", "capability": "domain_specialization_health", "topic": "domain_specialization_health", "source": "multicapability_bootstrap"}
{"instruction": "Extract entities from: 'Alice joined Acme Corp in Nairobi on 12 Jan 2025.'", "response": "PERSON: Alice; ORG: Acme Corp; LOCATION: Nairobi; DATE: 12 Jan 2025.", "capability": "nlp_entity_extraction", "topic": "nlp_entity_extraction", "source": "multicapability_bootstrap"}
{"instruction": "Detect the user intent: 'Can you generate pytest tests for this function?'", "response": "Intent classification result: code_test_generation_request.", "capability": "nlp_intent_recognition", "topic": "nlp_intent_recognition", "source": "multicapability_bootstrap"}
{"instruction": "Question: What does HTTP 404 indicate?", "response": "HTTP 404 indicates the requested resource was not found on the server.", "capability": "nlp_question_answering", "topic": "nlp_question_answering", "source": "multicapability_bootstrap"}
{"instruction": "Summarize: Q3 revenue grew but margins fell due to logistics costs.", "response": "Revenue increased in Q3 while margins declined because logistics costs rose.", "capability": "nlp_summarization", "topic": "nlp_summarization", "source": "multicapability_bootstrap"}
{"instruction": "Classify sentiment: 'The app is fast but crashes often.'", "response": "Label: mixed sentiment with positive speed feedback and negative stability issues.", "capability": "nlp_text_classification", "topic": "nlp_text_classification", "source": "multicapability_bootstrap"}
{"instruction": "Translate to French: 'Data quality drives model quality.'", "response": "Les donnees de qualite ameliorent la qualite du modele.", "capability": "nlp_translation", "topic": "nlp_translation", "source": "multicapability_bootstrap"}
{"instruction": "Design baseline for churn prediction.", "response": "Use stratified split, train baseline classifier, tune threshold, and report precision recall F1 and ROC AUC.", "capability": "predictive_classification", "topic": "predictive_classification", "source": "multicapability_bootstrap"}
{"instruction": "What is a simple recommendation-system baseline?", "response": "Start with popularity baseline, then item co-occurrence, and evaluate ranking with recall at k and ndcg.", "capability": "predictive_recommendation", "topic": "predictive_recommendation", "source": "multicapability_bootstrap"}
{"instruction": "How to train a model to predict house price from tabular features?", "response": "Prepare cleaned features, split train and validation, fit a regression baseline, evaluate MAE and RMSE, then iterate.", "capability": "predictive_regression", "topic": "predictive_regression", "source": "multicapability_bootstrap"}
{"instruction": "Outline a demand forecasting workflow for monthly sales.", "response": "Build time-indexed series, model trend and seasonality, validate on rolling windows, and forecast by horizon.", "capability": "predictive_time_series", "topic": "predictive_time_series", "source": "multicapability_bootstrap"}
{"instruction": "Premise: Every encrypted backup is stored offsite. Premise: Backup B is encrypted. Infer conclusion.", "response": "Backup B is stored offsite.", "capability": "reasoning_deduction_inference", "topic": "reasoning_deduction_inference", "source": "multicapability_bootstrap"}
{"instruction": "If all APIs require auth and this endpoint is an API endpoint, what follows?", "response": "The endpoint requires authentication by logical deduction.", "capability": "reasoning_logical", "topic": "reasoning_logical", "source": "multicapability_bootstrap"}
{"instruction": "Plan how to debug a failing integration test in a backend service.", "response": "Step 1 reproduce failure, step 2 isolate dependency, step 3 inspect logs, step 4 patch root cause, step 5 rerun tests.", "capability": "reasoning_multistep", "topic": "reasoning_multistep", "source": "multicapability_bootstrap"}
{"instruction": "Find the next number in the sequence: 2, 6, 12, 20, 30.", "response": "The differences are 4, 6, 8, 10 so the next difference is 12 and the next value is 42.", "capability": "reasoning_pattern_recognition", "topic": "reasoning_pattern_recognition", "source": "multicapability_bootstrap"}
{"instruction": "How should an agent execute an external API integration task?", "response": "Validate endpoint contract, send authenticated request, handle retries and timeouts, validate schema, and normalize outputs.", "capability": "tool_use_api_calls", "topic": "tool_use_api_calls", "source": "multicapability_bootstrap"}
{"instruction": "User asks to validate a Python snippet. What tool actions should the agent take?", "response": "Open file, run the script in the virtual environment, inspect traceback, patch minimal fix, rerun, and summarize results.", "capability": "tool_use_code_execution", "topic": "tool_use_code_execution", "source": "multicapability_bootstrap"}
{"instruction": "How should an agent run shell commands safely and effectively?", "response": "Use scoped non-destructive commands, inspect exit codes and output, iterate minimal fixes, and verify with tests.", "capability": "tool_use_command_execution", "topic": "tool_use_command_execution", "source": "multicapability_bootstrap"}
{"instruction": "Plan safe database operations for a data patch request.", "response": "Inspect schema, run read-only preview, create backup, execute transaction update, verify row counts, then commit.", "capability": "tool_use_database_ops", "topic": "tool_use_database_ops", "source": "multicapability_bootstrap"}
{"instruction": "How should an assistant fetch latest information from the web?", "response": "Use focused web search, prioritize recent primary sources, open relevant pages, extract key facts, and cite sources.", "capability": "web_information_retrieval", "topic": "web_information_retrieval", "source": "multicapability_bootstrap"}
{"instruction": "How should an assistant synthesize multiple web sources into one answer?", "response": "Cross-check source agreement, compare publication dates, capture differences, and deliver a cited synthesized conclusion.", "capability": "web_source_synthesis", "topic": "web_source_synthesis", "source": "multicapability_bootstrap"}123456789101112131415161718192021python-dotenvPyPDF2python-docxSpeechRecognitionpyttsx3pyaudiorequestsbeautifulsoup4numpysympyrapidfuzzpsutilopencv-pythonpillowpytesseracttorchdatasetstransformershuggingface_hubspacylanguage-tool-python123version https://git-lfs.github.com/spec/v1oid sha256:7531fff3211176e3bd24553d4b285d73bbf5043e5eec30af080dab4fea202bb2size 32127494123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280import mathimport refrom collections import Counterfrom dataclasses import dataclassfrom typing import Dict, List, Optional, Tuple
import torchimport torch.nn as nnimport torch.nn.functional as F
TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_]+|[^\w\s]", re.UNICODE)
class WordTokenizer: PAD_TOKEN = "<pad>" BOS_TOKEN = "<bos>" EOS_TOKEN = "<eos>" UNK_TOKEN = "<unk>"
def __init__(self): self.token_to_id: Dict[str, int] = {} self.id_to_token: Dict[int, str] = {} self.pad_id = -1 self.bos_id = -1 self.eos_id = -1 self.unk_id = -1
@property def vocab_size(self) -> int: return len(self.token_to_id)
@staticmethod def _split(text: str) -> List[str]: return TOKEN_PATTERN.findall((text or "").strip())
def fit(self, texts: List[str], vocab_size: int = 8000, min_freq: int = 2): counts = Counter() for text in texts: counts.update(self._split(text))
special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN] for token in special_tokens: self._add_token(token)
for token, freq in counts.most_common(max(0, vocab_size - len(special_tokens))): if freq < min_freq: continue if token not in self.token_to_id: self._add_token(token)
self.pad_id = self.token_to_id[self.PAD_TOKEN] self.bos_id = self.token_to_id[self.BOS_TOKEN] self.eos_id = self.token_to_id[self.EOS_TOKEN] self.unk_id = self.token_to_id[self.UNK_TOKEN]
def _add_token(self, token: str): idx = len(self.token_to_id) self.token_to_id[token] = idx self.id_to_token[idx] = token
def encode(self, text: str, add_bos: bool = False, add_eos: bool = False) -> List[int]: ids = [self.token_to_id.get(tok, self.unk_id) for tok in self._split(text)] if add_bos: ids = [self.bos_id] + ids if add_eos: ids = ids + [self.eos_id] return ids
def decode(self, ids: List[int]) -> str: tokens = [] for idx in ids: token = self.id_to_token.get(int(idx), self.UNK_TOKEN) if token in {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}: continue tokens.append(token)
text = " ".join(tokens) text = re.sub(r"\s+([.,!?;:)\]\}])", r"\1", text) text = re.sub(r"([([\{])\s+", r"\1", text) text = re.sub(r"\s+", " ", text) return text.strip()
def to_state(self) -> Dict: return { "token_to_id": self.token_to_id, "id_to_token": {str(k): v for k, v in self.id_to_token.items()}, "pad_id": self.pad_id, "bos_id": self.bos_id, "eos_id": self.eos_id, "unk_id": self.unk_id, }
@classmethod def from_state(cls, state: Dict): tok = cls() tok.token_to_id = dict(state.get("token_to_id", {})) tok.id_to_token = {int(k): v for k, v in state.get("id_to_token", {}).items()} tok.pad_id = int(state.get("pad_id", -1)) tok.bos_id = int(state.get("bos_id", -1)) tok.eos_id = int(state.get("eos_id", -1)) tok.unk_id = int(state.get("unk_id", -1)) return tok
@dataclassclass TinyConfig: vocab_size: int block_size: int = 256 n_layer: int = 4 n_head: int = 4 n_embd: int = 256 dropout: float = 0.1
class CausalSelfAttention(nn.Module): def __init__(self, config: TinyConfig): super().__init__() assert config.n_embd % config.n_head == 0 self.n_head = config.n_head self.head_dim = config.n_embd // config.n_head self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd) self.proj = nn.Linear(config.n_embd, config.n_embd) self.attn_drop = nn.Dropout(config.dropout) self.resid_drop = nn.Dropout(config.dropout) self.register_buffer( "mask", torch.tril(torch.ones(config.block_size, config.block_size)).view( 1, 1, config.block_size, config.block_size ), )
def forward(self, x): b, t, c = x.size() qkv = self.qkv(x) q, k, v = qkv.split(c, dim=2) q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2) k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2) v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2)
att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim) att = att.masked_fill(self.mask[:, :, :t, :t] == 0, float("-inf")) att = F.softmax(att, dim=-1) att = self.attn_drop(att) y = att @ v y = y.transpose(1, 2).contiguous().view(b, t, c) y = self.resid_drop(self.proj(y)) return y
class MLP(nn.Module): def __init__(self, config: TinyConfig): super().__init__() self.fc = nn.Linear(config.n_embd, 4 * config.n_embd) self.proj = nn.Linear(4 * config.n_embd, config.n_embd) self.drop = nn.Dropout(config.dropout)
def forward(self, x): x = self.fc(x) x = F.gelu(x) x = self.proj(x) x = self.drop(x) return x
class Block(nn.Module): def __init__(self, config: TinyConfig): super().__init__() self.ln1 = nn.LayerNorm(config.n_embd) self.attn = CausalSelfAttention(config) self.ln2 = nn.LayerNorm(config.n_embd) self.mlp = MLP(config)
def forward(self, x): x = x + self.attn(self.ln1(x)) x = x + self.mlp(self.ln2(x)) return x
class TinyCausalLM(nn.Module): def __init__(self, config: TinyConfig): super().__init__() self.config = config self.token_emb = nn.Embedding(config.vocab_size, config.n_embd) self.pos_emb = nn.Embedding(config.block_size, config.n_embd) self.drop = nn.Dropout(config.dropout) self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)]) self.ln_f = nn.LayerNorm(config.n_embd) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.apply(self._init_weights)
@staticmethod def _init_weights(module): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward( self, idx: torch.Tensor, targets: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: b, t = idx.size() if t > self.config.block_size: raise ValueError("Sequence length exceeds block size.")
pos = torch.arange(0, t, dtype=torch.long, device=idx.device).unsqueeze(0) x = self.token_emb(idx) + self.pos_emb(pos) x = self.drop(x) for block in self.blocks: x = block(x) x = self.ln_f(x) logits = self.lm_head(x)
loss = None if targets is not None: loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100, ) return logits, loss
@torch.no_grad() def generate( self, idx: torch.Tensor, max_new_tokens: int = 128, temperature: float = 0.8, top_k: int = 40, top_p: float = 0.95, repetition_penalty: float = 1.12, min_new_tokens: int = 0, eos_id: int = 2, stop_token_ids: Optional[List[int]] = None, ) -> torch.Tensor: stop_ids = set(stop_token_ids or []) if eos_id >= 0: stop_ids.add(eos_id) start_len = idx.size(1)
for _ in range(max_new_tokens): idx_cond = idx[:, -self.config.block_size :] logits, _ = self(idx_cond) logits = logits[:, -1, :] / max(temperature, 1e-6)
if repetition_penalty > 1.0: for b in range(idx.size(0)): seen = set(int(t) for t in idx[b].tolist()) for token_id in seen: value = logits[b, token_id] if value >= 0: logits[b, token_id] = value / repetition_penalty else: logits[b, token_id] = value * repetition_penalty
if top_k > 0: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float("inf")
if 0.0 < top_p < 1.0: sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) sorted_probs = F.softmax(sorted_logits, dim=-1) cumulative_probs = torch.cumsum(sorted_probs, dim=-1) sorted_mask = cumulative_probs > top_p sorted_mask[..., 0] = False mask = torch.zeros_like(sorted_mask, dtype=torch.bool) mask.scatter_(dim=-1, index=sorted_indices, src=sorted_mask) logits = logits.masked_fill(mask, -float("inf"))
probs = F.softmax(logits, dim=-1) next_token = torch.multinomial(probs, num_samples=1) idx = torch.cat((idx, next_token), dim=1) generated = idx.size(1) - start_len if generated < max(0, int(min_new_tokens)): continue if int(next_token.item()) in stop_ids: break return idx1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120import jsonimport randomimport refrom collections import defaultdictfrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence
TOPIC_TO_CAPABILITY = { "python_coding": "code_generation", "web_development": "code_generation", "automation": "tool_use_agentic", "data_processing": "data_analysis", "academic_writing": "academic_writing", "creative_writing": "humanized_writing", "greetings": "conversation_management", "api_parameters": "instruction_following", "api_response_format": "output_quality_controls", "mathematics": "math_reasoning", "linear_algebra": "complex_quant", "translation": "nlp_translation", "summarization": "nlp_summarization", "classification": "nlp_text_classification",}
KB_CATEGORY_TO_CAPABILITY = { "programming": "code_generation", "api": "tool_use_agentic", "mathematics": "math_reasoning", "linear_algebra": "complex_quant", "ai_ml": "data_science_ml", "academic": "academic_research_support", "writing": "academic_writing", "networking": "tool_use_agentic", "general": "instruction_following",}
BENCH_CAPABILITIES = { "instruction_following", "conversation_management", "code_generation", "code_representation", "code_edit_refactor", "debugging", "testing", "math_reasoning", "complex_quant", "data_analysis", "data_science_ml", "academic_research_support", "academic_writing", "humanized_writing", "originality_integrity_ethics", "tool_use_agentic", "image_workflow", "voice_workflow", "output_quality_controls", "nlp_text_classification", "nlp_question_answering", "nlp_translation", "nlp_summarization", "nlp_intent_recognition", "nlp_entity_extraction", "reasoning_logical", "reasoning_multistep", "reasoning_pattern_recognition", "reasoning_deduction_inference", "predictive_regression", "predictive_classification", "predictive_time_series", "predictive_recommendation", "tool_use_code_execution", "tool_use_api_calls", "tool_use_database_ops", "tool_use_command_execution", "web_information_retrieval", "web_source_synthesis", "code_completion", "code_bug_detection", "code_multifile_reasoning", "cv_object_detection", "cv_face_recognition", "cv_medical_image_analysis", "cv_ocr", "audio_speech_to_text", "audio_text_to_speech", "audio_speaker_recognition", "domain_specialization_finance", "domain_specialization_health", "domain_specialization_coding",}
BLOCKED_PATTERNS = [ re.compile(r"\bturnitin\b", flags=re.IGNORECASE), re.compile(r"\bbypass\b", flags=re.IGNORECASE), re.compile(r"\bevad(e|ing)\b", flags=re.IGNORECASE), re.compile(r"\bplagiarism detector\b", flags=re.IGNORECASE),]
FALLBACK_CAPABILITY_SEEDS = [ { "capability": "code_representation", "instruction": "Explain this Python function in plain language and summarize its time complexity: def dedupe(items): return list(dict.fromkeys(items)).", "response": "It removes duplicates while preserving first-seen order by routing values through dictionary keys. Average runtime is O(n), with O(n) memory.", }, { "capability": "code_edit_refactor", "instruction": "Refactor for readability: total=0; for i in range(len(nums)): total=total+nums[i]", "response": "Prefer total = sum(nums). If explicit iteration is required, use for value in nums: total += value to avoid index-only loops.", }, { "capability": "debugging", "instruction": "A Python function crashes with TypeError int plus str. How should the assistant respond?", "response": "Ask for the failing line, inspect input types, convert numeric strings before arithmetic, and add type validation near function entry.", }, { "capability": "testing", "instruction": "Create a minimal test checklist for a CSV parser.", "response": "Cover valid rows, missing required columns, unknown columns, empty input, malformed separators, unicode text, and one regression case per fixed bug.", }, { "capability": "conversation_management", "instruction": "How should the assistant handle a mid-task requirement change?", "response": "Acknowledge the change, summarize what shifted, confirm tradeoffs, and continue execution from the updated objective.", }, { "capability": "complex_quant", "instruction": "Outline concise steps for constrained optimization with Lagrange multipliers.", "response": "Define objective and constraint, build the Lagrangian, compute partial derivatives, solve the system, and verify feasible extrema.", }, { "capability": "data_analysis", "instruction": "What first-pass checks should be run on a sales CSV?", "response": "Validate schema and types, profile missing values, compute profit metrics, inspect outliers, and analyze time/region trends before conclusions.", }, { "capability": "data_science_ml", "instruction": "Provide a baseline workflow for binary classification on tabular data.", "response": "Create stratified train/validation split, train a simple baseline, evaluate precision-recall-F1/ROC-AUC, inspect feature effects, then iterate with cross-validation.", }, { "capability": "academic_research_support", "instruction": "How should an assistant summarize a research paper?", "response": "Present research question, method, data, main findings, limits, and implications, while separating reported evidence from interpretation.", }, { "capability": "humanized_writing", "instruction": "Rewrite this in a natural tone: Your request has been processed successfully.", "response": "Done, your request was processed successfully.", }, { "capability": "originality_integrity_ethics", "instruction": "How can a student keep an essay original while using sources?", "response": "Draft your own argument first, paraphrase with fresh structure, quote sparingly, and cite every borrowed idea accurately.", }, { "capability": "image_workflow", "instruction": "Create an image-generation prompt for realistic wireless earbuds.", "response": "Prompt: studio photo of matte black wireless earbuds and open case on neutral gradient, 85mm lens look, soft key light, high detail. Negative: blur, watermark, distorted geometry.", }, { "capability": "voice_workflow", "instruction": "Design a voice assistant flow for booking a dentist appointment.", "response": "Flow: greet, confirm intent, collect date/time/location, propose slots, confirm selected slot, and provide fallback prompts for unclear speech.", }, { "capability": "instruction_following", "instruction": "Return a strict two-step answer for setting up a Python virtual environment.", "response": "1. Create the environment with python -m venv .venv. 2. Activate it and install dependencies from requirements.txt.", }, { "capability": "code_generation", "instruction": "Write a Python function that returns whether a number is even.", "response": "def is_even(value: int) -> bool:\n return value % 2 == 0", }, { "capability": "math_reasoning", "instruction": "Solve 3x + 5 = 20.", "response": "Subtract 5 from both sides to get 3x = 15, then divide by 3, so x = 5.", }, { "capability": "academic_writing", "instruction": "Write one formal sentence about reproducibility in machine learning.", "response": "Reproducibility in machine learning requires transparent reporting of data, preprocessing, model settings, and evaluation protocols.", }, { "capability": "tool_use_agentic", "instruction": "User asks for a bug fix in a repository with failing tests. Provide a concise tool-use plan.", "response": "Inspect files and failing logs, reproduce with targeted tests, patch minimal code, rerun tests, and summarize changes with file references.", }, { "capability": "web_information_retrieval", "instruction": "How should an assistant fetch current information from the web for a user query?", "response": "Form focused search queries, prioritize primary and recent sources, open relevant pages, extract key facts, and return a concise answer with sources.", }, { "capability": "web_source_synthesis", "instruction": "How should an assistant synthesize findings from multiple web sources?", "response": "Cross-check source agreement, note publication dates, summarize consensus and disagreements, and cite the final sources used.", }, { "capability": "output_quality_controls", "instruction": "How should a model respond when user requests strict JSON output only?", "response": "Return valid JSON only, without markdown or extra prose, and keep keys stable and required fields explicit.", },]
def _read_json(path: Path) -> Dict: with open(path, "r", encoding="utf-8") as f: return json.load(f)
def _read_jsonl(path: Path) -> List[Dict]: rows: List[Dict] = [] if not path.exists(): return rows with open(path, "r", encoding="utf-8") as f: for line in f: text = line.strip() if not text: continue try: item = json.loads(text) except Exception: continue if isinstance(item, dict): rows.append(item) return rows
def _resolve_optional_path(path_text: str, anchors: Sequence[Path]) -> Path: target = Path(path_text) if target.is_absolute(): return target
candidates: List[Path] = [target] for anchor in anchors: candidates.append(anchor / target)
seen = set() unique_candidates: List[Path] = [] for candidate in candidates: norm = str(candidate) if norm in seen: continue seen.add(norm) unique_candidates.append(candidate)
for candidate in unique_candidates: if candidate.exists(): return candidate return target
def _clean_text(text: str) -> str: text = (text or "").replace("\r\n", "\n").replace("\r", "\n") text = "\n".join(line.strip() for line in text.split("\n")) return text.strip()
def _normalize_key(text: str) -> str: return re.sub(r"\s+", " ", (text or "").strip().lower())
def _token_count(text: str) -> int: return len(re.findall(r"[a-zA-Z0-9_']+", text or ""))
def _symbol_noise_ratio(text: str) -> float: if not text: return 1.0 valid = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,;:!?()[]{}'\"`-_/@#$%&*+=<>|\\\n\t") bad = sum(1 for ch in text if ch not in valid) return bad / max(1, len(text))
def _contains_blocked_pattern(text: str) -> bool: raw = text or "" return any(pattern.search(raw) for pattern in BLOCKED_PATTERNS)
def _looks_reference_noise(text: str) -> bool: lowered = (text or "").lower() if not lowered: return True if lowered.startswith(("exercise ", "chapter ", "section ", "?exercise ")): return True if "online edition (c)" in lowered: return True if re.search(r"\.\s*\.\s*\.\s*\.\s*\d{2,}", lowered): return True if "contents" in lowered and lowered.count("chapter") >= 2: return True if re.search(r"([:;.,\"'`_\\/\-\=\(\)\[\]\{\}])\1{4,}", lowered): return True return False
def _text_quality_ok( text: str, min_alpha_ratio: float = 0.20, max_control_chars: int = 0, max_symbol_noise_ratio: float = 0.12,) -> bool: if not text: return False control = sum(1 for ch in text if ord(ch) < 32 and ch not in {"\n", "\t"}) if control > max_control_chars: return False alpha = sum(1 for ch in text if ch.isalpha()) ratio = alpha / max(1, len(text)) if ratio < min_alpha_ratio: return False if _symbol_noise_ratio(text) > max_symbol_noise_ratio: return False return True
def _looks_pdf_noise(text: str) -> bool: lowered = (text or "").lower() words = re.findall(r"[a-zA-Z0-9_']+", lowered) if not words: return True
numeric = sum(1 for w in words if w.isdigit()) numeric_ratio = numeric / max(1, len(words)) if numeric_ratio > 0.22: return True
dotted_runs = lowered.count("...") + lowered.count(". . .") if dotted_runs >= 4: return True
if "contents" in lowered and lowered.count("chapter") >= 3: return True
if _looks_reference_noise(text): return True
return False
def _guess_pdf_topic(filename: str) -> str: name = (filename or "").lower() if any(k in name for k in ["python", "code", "program", "react", "web-development", "bootstrap"]): return "python_coding" if any(k in name for k in ["math", "algebra", "calculus"]): return "mathematics" if any(k in name for k in ["deep", "ml", "ai", "learning"]): return "ai_ml" return "academic_writing"
def _infer_capability(instruction: str, response: str, source: str, topic: str = "") -> str: topic_key = (topic or "").strip().lower() if topic_key in TOPIC_TO_CAPABILITY: return TOPIC_TO_CAPABILITY[topic_key] if topic_key in KB_CATEGORY_TO_CAPABILITY: return KB_CATEGORY_TO_CAPABILITY[topic_key]
merged = f"{instruction} {response}".lower() src = (source or "").lower() if "capability_pack" in src or "capability_seed" in src: if topic_key in BENCH_CAPABILITIES: return topic_key if any(k in merged for k in ["debug", "traceback", "exception", "stack trace"]): return "debugging" if any(k in merged for k in ["spam", "sentiment", "text classification", "label this text"]): return "nlp_text_classification" if any(k in merged for k in ["translate", "translation", "from english to"]): return "nlp_translation" if any(k in merged for k in ["summarize", "summary", "tl;dr"]): return "nlp_summarization" if any(k in merged for k in ["named entity", "entity extraction", "extract entities"]): return "nlp_entity_extraction" if any(k in merged for k in ["intent", "user intent", "classify intent"]): return "nlp_intent_recognition" if any(k in merged for k in ["question answering", "answer the question", "qa system"]): return "nlp_question_answering" if any(k in merged for k in ["unit test", "pytest", "test case", "integration test"]): return "testing" if any(k in merged for k in ["refactor", "clean this code", "improve readability"]): return "code_edit_refactor" if any(k in merged for k in ["explain this code", "time complexity", "big-o"]): return "code_representation" if any(k in merged for k in ["dataset", "pandas", "analysis", "plot", "visualization"]): return "data_analysis" if any(k in merged for k in ["cross-validation", "feature engineering", "classification", "regression model"]): return "data_science_ml" if any(k in merged for k in ["regression forecast", "predict numeric", "price prediction"]): return "predictive_regression" if any(k in merged for k in ["binary classification", "churn prediction", "class probability"]): return "predictive_classification" if any(k in merged for k in ["time series", "seasonality", "arima", "forecast horizon"]): return "predictive_time_series" if any(k in merged for k in ["recommendation", "collaborative filtering", "ranking model"]): return "predictive_recommendation" if any(k in merged for k in ["paper", "methodology", "research question", "literature review"]): return "academic_research_support" if any(k in merged for k in ["essay", "citation", "thesis", "academic paragraph"]): return "academic_writing" if any(k in merged for k in ["voice assistant", "speech", "transcript"]): return "voice_workflow" if any(k in merged for k in ["speech-to-text", "asr", "transcribe audio"]): return "audio_speech_to_text" if any(k in merged for k in ["text-to-speech", "tts", "voice synthesis"]): return "audio_text_to_speech" if any(k in merged for k in ["speaker recognition", "speaker verification", "voiceprint"]): return "audio_speaker_recognition" if any(k in merged for k in ["image prompt", "lighting", "negative prompt"]): return "image_workflow" if any(k in merged for k in ["object detection", "bounding box", "yolo"]): return "cv_object_detection" if any(k in merged for k in ["face recognition", "facial embedding"]): return "cv_face_recognition" if any(k in merged for k in ["medical image", "x-ray", "ct scan", "mri"]): return "cv_medical_image_analysis" if any(k in merged for k in ["ocr", "extract text from image"]): return "cv_ocr" if any(k in merged for k in ["tool-use", "workflow", "steps", "plan"]): return "tool_use_agentic" if any(k in merged for k in ["run code", "python execution", "sandbox execution"]): return "tool_use_code_execution" if any(k in merged for k in ["call api", "rest api", "endpoint"]): return "tool_use_api_calls" if any(k in merged for k in ["sql", "database", "query table"]): return "tool_use_database_ops" if any(k in merged for k in ["shell command", "terminal command", "powershell"]): return "tool_use_command_execution" if any(k in merged for k in ["web search", "search the web", "browse the web", "fetch online", "latest information"]): return "web_information_retrieval" if any(k in merged for k in ["synthesize sources", "compare sources", "cross-check sources", "cite sources"]): return "web_source_synthesis" if any(k in merged for k in ["code completion", "complete this function"]): return "code_completion" if any(k in merged for k in ["bug detection", "find bug", "fault localization"]): return "code_bug_detection" if any(k in merged for k in ["multi-file", "across files", "cross-file"]): return "code_multifile_reasoning" if any(k in merged for k in ["equation", "solve", "integral", "derivative", "probability"]): return "math_reasoning" if any(k in merged for k in ["deduce", "inference", "premise", "conclusion"]): return "reasoning_deduction_inference" if any(k in merged for k in ["step-by-step", "multi-step", "decompose"]): return "reasoning_multistep" if any(k in merged for k in ["pattern recognition", "sequence pattern"]): return "reasoning_pattern_recognition" if any(k in merged for k in ["logical reasoning", "logic puzzle"]): return "reasoning_logical" if any(k in merged for k in ["finance domain", "financial analysis", "valuation"]): return "domain_specialization_finance" if any(k in merged for k in ["health domain", "clinical", "medical protocol"]): return "domain_specialization_health" if any(k in merged for k in ["coding domain", "software architecture", "programming best practices"]): return "domain_specialization_coding" return "instruction_following"
def _row_quality_ok(instruction: str, response: str, quality_min_alpha_ratio: float) -> bool: if _contains_blocked_pattern(instruction) or _contains_blocked_pattern(response): return False if _token_count(instruction) < 3 or _token_count(response) < 3: return False if _looks_reference_noise(instruction) or _looks_reference_noise(response): return False if not _text_quality_ok(instruction, min_alpha_ratio=quality_min_alpha_ratio, max_symbol_noise_ratio=0.12): return False if not _text_quality_ok(response, min_alpha_ratio=quality_min_alpha_ratio, max_symbol_noise_ratio=0.18): return False return True
def _extract_pdf_text(pdf_path: Path, max_pages: int) -> str: try: import PyPDF2 except Exception: return ""
chunks: List[str] = [] try: with open(pdf_path, "rb") as f: reader = PyPDF2.PdfReader(f) total = len(reader.pages) page_cap = min(max_pages, total) for i in range(page_cap): text = (reader.pages[i].extract_text() or "").strip() if text: chunks.append(text) except Exception: return ""
return _clean_text("\n\n".join(chunks))
def _build_pdf_samples( docs_pdf_dir: str, max_docs_pdf_files: int, max_pdf_pages_per_file: int, pdf_chunk_chars: int, max_pdf_samples: int, enforce_quality_filter: bool, quality_min_alpha_ratio: float,) -> List[Dict[str, str]]: base = Path(docs_pdf_dir) if not base.exists() or max_pdf_samples <= 0 or max_docs_pdf_files <= 0: return []
pdf_files = sorted(base.glob("*.pdf"))[:max_docs_pdf_files] if not pdf_files: return []
templates = [ "Summarize the key ideas from '{title}' section {idx}.", "Explain the core concepts in this excerpt from '{title}' (part {idx}).", "Provide study notes for '{title}' section {idx}.", ]
rows: List[Dict[str, str]] = [] for pdf in pdf_files: title = pdf.stem.replace("_", " ").strip() or pdf.name topic = _guess_pdf_topic(pdf.name) text = _extract_pdf_text(pdf, max_pages=max_pdf_pages_per_file) if len(text) < 300: continue
# Keep chunking deterministic and bounded so training rebuild is stable. section_idx = 1 for start in range(0, len(text), pdf_chunk_chars): if len(rows) >= max_pdf_samples: return rows segment = text[start : start + pdf_chunk_chars] segment = re.sub(r"\s+", " ", segment).strip() if len(segment) < 220: continue if _looks_pdf_noise(segment): continue
instruction = templates[(section_idx - 1) % len(templates)].format(title=title, idx=section_idx) section_idx += 1 capability = _infer_capability(instruction, segment, source="docs_pdf", topic=topic)
if enforce_quality_filter: if not _text_quality_ok(instruction, min_alpha_ratio=0.30): continue if not _text_quality_ok(segment, min_alpha_ratio=quality_min_alpha_ratio): continue
rows.append( { "instruction": instruction, "response": segment, "source": "docs_pdf", "topic": topic or capability, "capability": capability, } )
return rows
def _cap_rows_by_source(rows: List[Dict[str, str]], source_limits: Dict[str, int], seed: int) -> List[Dict[str, str]]: if not source_limits: return rows rng = random.Random(seed) buckets: Dict[str, List[Dict[str, str]]] = defaultdict(list) passthrough: List[Dict[str, str]] = [] for row in rows: source = str(row.get("source", "")).split(":", 1)[0] if source in source_limits: buckets[source].append(row) else: passthrough.append(row)
kept = list(passthrough) for source, items in buckets.items(): limit = max(0, int(source_limits.get(source, len(items)))) if len(items) <= limit: kept.extend(items) continue shuffled = items[:] rng.shuffle(shuffled) kept.extend(shuffled[:limit]) return kept
def _cap_rows_by_capability(rows: List[Dict[str, str]], max_rows_per_capability: Optional[int], seed: int) -> List[Dict[str, str]]: if max_rows_per_capability is None: return rows limit = max(1, int(max_rows_per_capability)) rng = random.Random(seed) buckets: Dict[str, List[Dict[str, str]]] = defaultdict(list) for row in rows: capability = str(row.get("capability", "")).strip() buckets[capability].append(row)
kept: List[Dict[str, str]] = [] for capability, items in buckets.items(): if capability == "" or len(items) <= limit: kept.extend(items) continue shuffled = items[:] rng.shuffle(shuffled) kept.extend(shuffled[:limit]) return kept
def _inject_missing_capability_seeds(samples: List[Dict[str, str]]) -> None: present = {str(row.get("capability", "")).strip() for row in samples if row.get("capability")} for seed in FALLBACK_CAPABILITY_SEEDS: capability = seed["capability"] if capability in present: continue instruction = _clean_text(seed["instruction"]) response = _clean_text(seed["response"]) samples.append( { "instruction": instruction, "response": response, "source": "capability_seed_fallback", "topic": capability, "capability": capability, } ) present.add(capability)
def build_samples( training_path: str = "training_data.json", kb_path: str = "knowledge_base.json", max_kb_samples: int = 5000, kb_categories: Optional[Sequence[str]] = None, exclude_kb_categories: Optional[Sequence[str]] = None, include_training: bool = True, include_kb: bool = True, min_question_len: int = 4, max_question_len: int = 240, min_answer_len: int = 8, max_answer_len: int = 500, min_kb_confidence: float = 0.0, high_quality_only: bool = False, include_kb_aliases: bool = True, max_aliases_per_kb: int = 2, max_alias_samples: int = 2000, dedupe: bool = True, enforce_quality_filter: bool = True, quality_min_alpha_ratio: float = 0.20, include_docs_pdfs: bool = True, docs_pdf_dir: str = "docs", max_docs_pdf_files: int = 12, max_pdf_pages_per_file: int = 25, pdf_chunk_chars: int = 1100, max_pdf_samples: int = 1200, external_instruction_paths: Optional[Sequence[str]] = ( "datasets/dialogue_qa_flows.jsonl", "capability_pack.jsonl", "multicapability_bootstrap.jsonl", "adaptive_boost.jsonl", ), max_kb_per_category: Optional[int] = 160, max_dialogue_samples: int = 1800, max_capability_seed_rebalanced_samples: int = 900, max_rows_per_capability: Optional[int] = 180, rebalance_capabilities: bool = True, capability_registry_path: str = "capability_registry.json", min_rows_per_high_priority_capability: int = 80, min_rows_per_medium_priority_capability: int = 40, seed: int = 42,) -> List[Dict[str, str]]: random.seed(seed) training_data = _read_json(Path(training_path)) kb_data = _read_json(Path(kb_path))
samples: List[Dict[str, str]] = []
if include_training: for ex in training_data.get("training_examples", []): instruction = _clean_text(ex.get("instruction", ex.get("prompt", ""))) response = _clean_text(ex.get("response", "")) if len(instruction) < 4 or len(response) < 4: continue if enforce_quality_filter: if not _row_quality_ok(instruction, response, quality_min_alpha_ratio): continue topic = _clean_text(ex.get("topic", "")) capability = _infer_capability(instruction, response, source="training_data", topic=topic) samples.append( { "instruction": instruction, "response": response, "source": "training_data", "topic": topic or capability, "capability": capability, } )
if include_docs_pdfs: pdf_samples = _build_pdf_samples( docs_pdf_dir=docs_pdf_dir, max_docs_pdf_files=max_docs_pdf_files, max_pdf_pages_per_file=max_pdf_pages_per_file, pdf_chunk_chars=pdf_chunk_chars, max_pdf_samples=max_pdf_samples, enforce_quality_filter=enforce_quality_filter, quality_min_alpha_ratio=quality_min_alpha_ratio, ) samples.extend(pdf_samples)
if external_instruction_paths: anchor_paths: List[Path] = [Path.cwd(), Path(__file__).resolve().parent] for candidate_path in (training_path, kb_path): maybe = Path(candidate_path) if maybe.is_absolute(): anchor_paths.append(maybe.parent) elif maybe.exists(): anchor_paths.append(maybe.resolve().parent)
for ext_path in external_instruction_paths: resolved = _resolve_optional_path(ext_path, anchor_paths) for row in _read_jsonl(resolved): instruction = _clean_text(row.get("instruction", row.get("prompt", ""))) response = _clean_text(row.get("response", "")) source = _clean_text(row.get("source", "")) or "external_dialogue_qa" if len(instruction) < 4 or len(response) < 4: continue if len(instruction) > max_question_len or len(response) > max_answer_len * 4: # External dialogue turns can be longer than KB answers; keep bounded. continue if enforce_quality_filter: if not _row_quality_ok(instruction, response, quality_min_alpha_ratio): continue topic = _clean_text(str(row.get("topic", ""))) capability = _clean_text(str(row.get("capability", ""))) if not capability: capability = _infer_capability(instruction, response, source=source, topic=topic) samples.append( { "instruction": instruction, "response": response, "source": source, "topic": topic or capability, "capability": capability, } )
if kb_categories is None: kb_categories = ["programming", "api", "academic", "writing", "ai_ml", "networking", "mathematics", "general"] kb_categories = set(kb_categories) excluded = set(exclude_kb_categories or [])
if include_kb: kb_items = list(kb_data.items()) random.shuffle(kb_items)
added_kb = 0 added_alias = 0 per_category = defaultdict(int) for question, payload in kb_items: if added_kb >= max_kb_samples: break if not isinstance(payload, dict): continue category = payload.get("category") if category not in kb_categories or category in excluded: continue if max_kb_per_category is not None and per_category[category] >= max_kb_per_category: continue confidence = float(payload.get("confidence", 0.0) or 0.0) if confidence < min_kb_confidence: continue
answer = _clean_text(payload.get("answer", "")) question = _clean_text(question) if len(question) < min_question_len or len(answer) < min_answer_len: continue if len(question) > max_question_len or len(answer) > max_answer_len: continue if enforce_quality_filter: if not _row_quality_ok(question, answer, quality_min_alpha_ratio): continue if high_quality_only and not _is_high_quality_entry(question, answer, category): continue
capability = _infer_capability(question, answer, source="knowledge_base", topic=category) samples.append( { "instruction": question, "response": answer, "source": "knowledge_base", "topic": category or capability, "capability": capability, } ) added_kb += 1 per_category[category] += 1
if include_kb_aliases and added_alias < max_alias_samples: aliases = payload.get("aliases", []) if isinstance(aliases, list): for alias in aliases[:max_aliases_per_kb]: alias_text = _clean_text(str(alias)) if not alias_text: continue if len(alias_text) < min_question_len or len(alias_text) > max_question_len: continue if enforce_quality_filter and not _row_quality_ok(alias_text, answer, quality_min_alpha_ratio): continue samples.append( { "instruction": alias_text, "response": answer, "source": "knowledge_base_alias", "topic": category or capability, "capability": capability, } ) added_alias += 1 if added_alias >= max_alias_samples: break
_inject_missing_capability_seeds(samples)
if dedupe: unique = {} for row in samples: key = (_normalize_key(row["instruction"]), _normalize_key(row["response"])) if key not in unique: unique[key] = row samples = list(unique.values())
source_limits: Dict[str, int] = {} if max_dialogue_samples > 0: source_limits["dialogue"] = int(max_dialogue_samples) source_limits["external_dialogue_qa"] = int(max_dialogue_samples) source_limits["dialogue_qa_flows"] = int(max_dialogue_samples) if max_capability_seed_rebalanced_samples > 0: source_limits["capability_seed_rebalanced"] = int(max_capability_seed_rebalanced_samples) if source_limits: samples = _cap_rows_by_source(samples, source_limits=source_limits, seed=seed + 13)
samples = _cap_rows_by_capability(samples, max_rows_per_capability=max_rows_per_capability, seed=seed + 15)
if rebalance_capabilities: targets = _load_capability_targets( capability_registry_path=capability_registry_path, min_rows_per_high=min_rows_per_high_priority_capability, min_rows_per_medium=min_rows_per_medium_priority_capability, ) samples = _rebalance_capabilities(samples, targets=targets, seed=seed + 17)
random.shuffle(samples) return samples
def _is_high_quality_entry(question: str, answer: str, category: str) -> bool: q = question.lower() a = answer.lower() if any(noise in q for noise in ["exercise", "chapter", "contents"]): return False if any(noise in a for noise in ["exercise", "chapter", "contents"]): return False if category == "general": return False if "?" not in question and not q.startswith(("what", "how", "why", "when", "where", "who", "can", "is", "are", "do", "does")): return False return True
def _load_capability_targets( capability_registry_path: str, min_rows_per_high: int, min_rows_per_medium: int,) -> Dict[str, int]: default_targets = { capability: min_rows_per_medium for capability in BENCH_CAPABILITIES } path = Path(capability_registry_path) if not path.exists(): return default_targets
try: payload = _read_json(path) except Exception: return default_targets
targets = dict(default_targets) for item in payload.get("capabilities", []): if not isinstance(item, dict): continue capability = str(item.get("id", "")).strip() if not capability: continue if item.get("enabled", True) is False: continue priority = str(item.get("train_priority", "medium")).strip().lower() if priority == "high": targets[capability] = max(targets.get(capability, 0), int(min_rows_per_high)) elif priority == "medium": targets[capability] = max(targets.get(capability, 0), int(min_rows_per_medium)) else: targets[capability] = max(targets.get(capability, 0), max(10, int(min_rows_per_medium // 2)))
return targets
def _rebalance_capabilities(samples: List[Dict[str, str]], targets: Dict[str, int], seed: int) -> List[Dict[str, str]]: rng = random.Random(seed) by_capability: Dict[str, List[Dict[str, str]]] = defaultdict(list) for row in samples: capability = str(row.get("capability", "")).strip() if not capability: continue by_capability[capability].append(row)
balanced = list(samples) for capability, target in targets.items(): pool = by_capability.get(capability, []) if not pool: continue if len(pool) >= target: continue needed = target - len(pool) for _ in range(needed): template = dict(rng.choice(pool)) source = str(template.get("source", "rebalanced")) template["source"] = f"{source}:rebalanced" balanced.append(template)
return balanced
def save_jsonl(samples: List[Dict[str, str]], out_path: str) -> None: path = Path(out_path) path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8") as f: for row in samples: f.write(json.dumps(row, ensure_ascii=False) + "\n")
def build_dataset_file( out_path: str = "models/tiny_model_dataset.jsonl", training_path: str = "training_data.json", kb_path: str = "knowledge_base.json", max_kb_samples: int = 5000, kb_categories: Optional[Sequence[str]] = None, exclude_kb_categories: Optional[Sequence[str]] = None, include_training: bool = True, include_kb: bool = True, min_question_len: int = 4, max_question_len: int = 240, min_answer_len: int = 8, max_answer_len: int = 500, min_kb_confidence: float = 0.0, high_quality_only: bool = False, include_kb_aliases: bool = True, max_aliases_per_kb: int = 2, max_alias_samples: int = 2000, dedupe: bool = True, enforce_quality_filter: bool = True, quality_min_alpha_ratio: float = 0.20, include_docs_pdfs: bool = True, docs_pdf_dir: str = "docs", max_docs_pdf_files: int = 12, max_pdf_pages_per_file: int = 25, pdf_chunk_chars: int = 1100, max_pdf_samples: int = 1200, external_instruction_paths: Optional[Sequence[str]] = ( "datasets/dialogue_qa_flows.jsonl", "capability_pack.jsonl", "multicapability_bootstrap.jsonl", "adaptive_boost.jsonl", ), max_kb_per_category: Optional[int] = 160, max_dialogue_samples: int = 1800, max_capability_seed_rebalanced_samples: int = 900, max_rows_per_capability: Optional[int] = 180, rebalance_capabilities: bool = True, capability_registry_path: str = "capability_registry.json", min_rows_per_high_priority_capability: int = 80, min_rows_per_medium_priority_capability: int = 40, seed: int = 42,) -> Dict[str, object]: samples = build_samples( training_path=training_path, kb_path=kb_path, max_kb_samples=max_kb_samples, kb_categories=kb_categories, exclude_kb_categories=exclude_kb_categories, include_training=include_training, include_kb=include_kb, min_question_len=min_question_len, max_question_len=max_question_len, min_answer_len=min_answer_len, max_answer_len=max_answer_len, min_kb_confidence=min_kb_confidence, high_quality_only=high_quality_only, include_kb_aliases=include_kb_aliases, max_aliases_per_kb=max_aliases_per_kb, max_alias_samples=max_alias_samples, dedupe=dedupe, enforce_quality_filter=enforce_quality_filter, quality_min_alpha_ratio=quality_min_alpha_ratio, include_docs_pdfs=include_docs_pdfs, docs_pdf_dir=docs_pdf_dir, max_docs_pdf_files=max_docs_pdf_files, max_pdf_pages_per_file=max_pdf_pages_per_file, pdf_chunk_chars=pdf_chunk_chars, max_pdf_samples=max_pdf_samples, external_instruction_paths=external_instruction_paths, max_kb_per_category=max_kb_per_category, max_dialogue_samples=max_dialogue_samples, max_capability_seed_rebalanced_samples=max_capability_seed_rebalanced_samples, max_rows_per_capability=max_rows_per_capability, rebalance_capabilities=rebalance_capabilities, capability_registry_path=capability_registry_path, min_rows_per_high_priority_capability=min_rows_per_high_priority_capability, min_rows_per_medium_priority_capability=min_rows_per_medium_priority_capability, seed=seed, ) save_jsonl(samples, out_path) training_count = sum(1 for s in samples if s["source"] == "training_data") docs_pdf_count = sum(1 for s in samples if s["source"] == "docs_pdf") external_count = sum( 1 for s in samples if s["source"].split(":", 1)[0] not in {"training_data", "docs_pdf", "knowledge_base", "knowledge_base_alias"} ) kb_count = sum(1 for s in samples if s["source"] == "knowledge_base") kb_alias_count = sum(1 for s in samples if s["source"] == "knowledge_base_alias") capability_counts: Dict[str, int] = defaultdict(int) for row in samples: capability = str(row.get("capability", "")).strip() if capability: capability_counts[capability] += 1 return { "total_samples": len(samples), "training_samples": training_count, "docs_pdf_samples": docs_pdf_count, "external_samples": external_count, "kb_samples": kb_count, "kb_alias_samples": kb_alias_count, "capability_counts": dict(sorted(capability_counts.items())), }
def build_curriculum_files( stage1_path: str = "models/tiny_model_stage1.jsonl", stage2_path: str = "models/tiny_model_stage2.jsonl", training_path: str = "training_data.json", kb_path: str = "knowledge_base.json", max_kb_samples_stage1: int = 1000, max_kb_samples_stage2: int = 4000, seed: int = 42,) -> Dict[str, Dict[str, object]]: stage1_stats = build_dataset_file( out_path=stage1_path, training_path=training_path, kb_path=kb_path, max_kb_samples=max_kb_samples_stage1, kb_categories=["programming", "api", "academic", "writing", "mathematics", "networking", "ai_ml"], exclude_kb_categories=["general"], include_training=True, include_kb=True, min_question_len=8, max_question_len=180, min_answer_len=20, max_answer_len=320, min_kb_confidence=0.85, high_quality_only=True, include_kb_aliases=True, max_aliases_per_kb=1, max_alias_samples=400, max_kb_per_category=90, max_dialogue_samples=700, max_capability_seed_rebalanced_samples=450, max_rows_per_capability=120, dedupe=True, enforce_quality_filter=True, quality_min_alpha_ratio=0.28, rebalance_capabilities=True, min_rows_per_high_priority_capability=45, min_rows_per_medium_priority_capability=24, seed=seed, )
stage2_stats = build_dataset_file( out_path=stage2_path, training_path=training_path, kb_path=kb_path, max_kb_samples=max_kb_samples_stage2, kb_categories=["programming", "api", "academic", "writing", "ai_ml", "networking", "mathematics", "general"], include_training=True, include_kb=True, min_question_len=4, max_question_len=240, min_answer_len=8, max_answer_len=500, min_kb_confidence=0.0, high_quality_only=False, include_kb_aliases=True, max_aliases_per_kb=1, max_alias_samples=1200, max_kb_per_category=120, max_dialogue_samples=1600, max_capability_seed_rebalanced_samples=800, max_rows_per_capability=180, dedupe=True, enforce_quality_filter=True, quality_min_alpha_ratio=0.24, rebalance_capabilities=True, min_rows_per_high_priority_capability=100, min_rows_per_medium_priority_capability=50, seed=seed, )
return {"stage1": stage1_stats, "stage2": stage2_stats}
if __name__ == "__main__": stats = build_dataset_file() print(stats)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467import astimport jsonimport refrom pathlib import Pathfrom typing import Dict, List, Tuple
import torch
from tiny_model_core import TinyCausalLM, TinyConfig, WordTokenizer
BENCHMARKS = [ { "capability": "instruction_following", "instruction": "Follow this exactly: return three bullet points about Python file handling and include one short example.", "expected_tokens": ["open", "with", "example"], "requires_structure": True, }, { "capability": "conversation_management", "instruction": "A user changed requirements mid-task. Provide a concise response that acknowledges change and continues with an updated plan.", "expected_tokens": ["changed", "plan", "continue"], "requires_structure": True, }, { "capability": "code_generation", "instruction": "Write a clean Python function to reverse a string. Keep it production-ready and clear.", "expected_tokens": ["def", "return"], }, { "capability": "code_representation", "instruction": "Explain what this code does and its complexity: def dedupe(items): return list(dict.fromkeys(items)).", "expected_tokens": ["duplicates", "order", "o("], }, { "capability": "code_edit_refactor", "instruction": "Refactor for readability: total=0; for i in range(len(nums)): total=total+nums[i]", "expected_tokens": ["sum", "for", "readability"], }, { "capability": "debugging", "instruction": "A script fails with TypeError unsupported operand types for + int and str. Give a concise debugging response.", "expected_tokens": ["type", "convert", "line"], }, { "capability": "testing", "instruction": "Create a focused test checklist for CSV parser behavior.", "expected_tokens": ["valid", "missing", "edge"], "requires_structure": True, }, { "capability": "math_reasoning", "instruction": "Solve x**2 - 4 = 0 and provide the final result clearly.", "expected_tokens": ["-2", "2"], }, { "capability": "complex_quant", "instruction": "Outline concise steps for solving constrained optimization with Lagrange multipliers.", "expected_tokens": ["objective", "constraint", "derivative"], "requires_structure": True, }, { "capability": "data_analysis", "instruction": "Describe a practical first-pass data analysis plan for a CSV with sales, costs, and dates.", "expected_tokens": ["missing", "outlier", "trend"], "requires_structure": True, }, { "capability": "data_science_ml", "instruction": "Provide a compact baseline workflow for binary classification on tabular data.", "expected_tokens": ["train", "validation", "f1"], "requires_structure": True, }, { "capability": "academic_research_support", "instruction": "Summarize how to review a research paper for a graduate-level reading group.", "expected_tokens": ["method", "limitations", "findings"], "requires_structure": True, }, { "capability": "academic_writing", "instruction": "Write a concise academic paragraph about cybersecurity governance with formal tone.", "expected_tokens": ["cybersecurity", "governance"], }, { "capability": "humanized_writing", "instruction": "Rewrite this sentence in a natural tone: Your request has been processed successfully.", "expected_tokens": ["processed", "successfully"], }, { "capability": "originality_integrity_ethics", "instruction": "How can someone keep an essay original while using sources responsibly?", "expected_tokens": ["citations", "paraphrase", "argument"], }, { "capability": "tool_use_agentic", "instruction": "A repository has failing tests. Provide an actionable tool-use plan to diagnose and fix the issue.", "expected_tokens": ["reproduce", "patch", "tests"], "requires_structure": True, }, { "capability": "image_workflow", "instruction": "Generate a structured prompt for an image model to create a realistic product photo of headphones.", "expected_tokens": ["prompt", "lighting", "negative"], "requires_structure": True, }, { "capability": "voice_workflow", "instruction": "Design a brief voice-assistant flow for booking an appointment.", "expected_tokens": ["confirm", "fallback", "time"], "requires_structure": True, }, { "capability": "output_quality_controls", "instruction": "State the response rules when the user requests strict JSON output.", "expected_tokens": ["valid", "json", "no extra"], }, { "capability": "nlp_text_classification", "instruction": "Classify sentiment: 'The UI is beautiful but the app crashes every hour.'", "expected_tokens": ["mixed", "positive", "negative"], }, { "capability": "nlp_translation", "instruction": "Translate to French: 'Data quality drives model quality.'", "expected_tokens": ["donnees", "qualite"], }, { "capability": "nlp_summarization", "instruction": "Summarize this in one sentence: Q3 revenue grew 12%, but margin fell because logistics costs rose.", "expected_tokens": ["revenue", "margin"], }, { "capability": "nlp_entity_extraction", "instruction": "Extract entities: 'Alice from Acme visited Nairobi on 12 Jan 2025.'", "expected_tokens": ["alice", "acme", "nairobi"], }, { "capability": "predictive_time_series", "instruction": "Provide a short time-series forecasting plan for monthly sales.", "expected_tokens": ["seasonality", "forecast", "horizon"], "requires_structure": True, }, { "capability": "predictive_recommendation", "instruction": "Give a baseline recommendation-system plan.", "expected_tokens": ["baseline", "ranking", "recall"], }, { "capability": "tool_use_code_execution", "instruction": "Describe how an agent should run and validate a Python script fix.", "expected_tokens": ["run", "traceback", "rerun"], "requires_structure": True, }, { "capability": "tool_use_database_ops", "instruction": "Provide safe steps for a production SQL data patch.", "expected_tokens": ["transaction", "backup", "verify"], "requires_structure": True, }, { "capability": "web_information_retrieval", "instruction": "Explain how an assistant should fetch the latest web information for a user question.", "expected_tokens": ["search", "source", "latest"], "requires_structure": True, }, { "capability": "web_source_synthesis", "instruction": "Describe how to synthesize multiple web sources into one grounded answer.", "expected_tokens": ["cross-check", "dates", "cite"], "requires_structure": True, }, { "capability": "cv_ocr", "instruction": "Describe a robust OCR pipeline for scanned invoices.", "expected_tokens": ["preprocess", "recognize", "json"], }, { "capability": "audio_speech_to_text", "instruction": "Outline a speech-to-text pipeline for meeting recordings.", "expected_tokens": ["segment", "transcript", "timestamps"], }, { "capability": "reasoning_deduction_inference", "instruction": "If all encrypted backups are offsite and backup B is encrypted, what can we conclude?", "expected_tokens": ["backup b", "offsite"], }, { "capability": "code_generation", "instruction": "Write a professional Python function to check if a number is prime, with clear naming.", "expected_tokens": ["def", "for", "return"], },]
def _load_capability_weights(registry_path: str = "capability_registry.json") -> Dict[str, float]: default = {} path = Path(registry_path) if not path.exists(): return default try: payload = json.loads(path.read_text(encoding="utf-8")) except Exception: return default
weights: Dict[str, float] = {} for item in payload.get("capabilities", []): if not isinstance(item, dict): continue capability = str(item.get("id", "")).strip() if not capability: continue priority = str(item.get("train_priority", "medium")).strip().lower() if priority == "high": weights[capability] = 1.0 elif priority == "medium": weights[capability] = 0.75 else: weights[capability] = 0.55 return weights
def _generate_response( model: TinyCausalLM, tokenizer: WordTokenizer, instruction: str, max_new_tokens: int = 100,) -> str: device = next(model.parameters()).device formatted = f"User: {instruction.strip()}\nAssistant:" ids = tokenizer.encode(formatted, add_bos=True, add_eos=False) if len(ids) > model.config.block_size: ids = ids[-model.config.block_size :] x = torch.tensor([ids], dtype=torch.long, device=device) out = model.generate( x, max_new_tokens=max_new_tokens, temperature=0.95, top_k=50, top_p=0.95, repetition_penalty=1.12, min_new_tokens=15, eos_id=tokenizer.eos_id, ) decoded = tokenizer.decode(out[0].tolist()) if "Assistant:" in decoded: decoded = decoded.split("Assistant:", 1)[1] for marker in ("User:", "System:"): if marker in decoded: decoded = decoded.split(marker, 1)[0] return decoded.strip()
def _extract_code_candidate(text: str) -> str: fence = re.search(r"```(?:python)?\s*(.*?)```", text, flags=re.IGNORECASE | re.DOTALL) if fence: return fence.group(1).strip() return text.strip()
def _score_code_response(response: str, expected_tokens: List[str]) -> float: score = 0.0 text = response.strip() if not text: return 0.0 lower = text.lower() if len(text) >= 24: score += 0.2
if any(token in lower for token in ["def ", "class ", "return", "import "]): score += 0.2
if expected_tokens: hits = sum(1 for tok in expected_tokens if tok.lower() in lower) score += 0.3 * (hits / len(expected_tokens))
candidate = _extract_code_candidate(text) try: ast.parse(candidate) score += 0.3 except Exception: pass
score += 0.2 * _professional_signal(text) return min(1.0, score)
def _score_math_response(response: str, expected_tokens: List[str]) -> float: text = response.strip().lower() if not text: return 0.0 score = 0.2 if expected_tokens: hits = sum(1 for tok in expected_tokens if tok.lower() in text) score += 0.8 * (hits / len(expected_tokens)) score += 0.2 * _professional_signal(response) return min(1.0, score)
def _score_academic_response(instruction: str, response: str, expected_tokens: List[str]) -> float: text = response.strip() lower = text.lower() score = 0.0
if len(text) >= 80: score += 0.4
sentences = [s for s in re.split(r"[.!?]+", text) if s.strip()] if len(sentences) >= 3: score += 0.2
if expected_tokens: hits = sum(1 for tok in expected_tokens if tok.lower() in lower) score += 0.2 * (hits / max(1, len(expected_tokens)))
instruction_words = {w for w in re.findall(r"[a-zA-Z]+", instruction.lower()) if len(w) > 4} overlap = sum(1 for w in instruction_words if w in lower) if overlap >= 2: score += 0.1
if any(w in lower for w in ["however", "therefore", "analysis", "research", "conclusion", "introduction"]): score += 0.1
score += 0.2 * _professional_signal(response) return min(1.0, score)
def _score_generic_response( instruction: str, response: str, expected_tokens: List[str], requires_structure: bool = False,) -> float: text = response.strip() if not text: return 0.0
lower = text.lower() score = 0.0
if len(text) >= 40: score += 0.25
if expected_tokens: hits = sum(1 for tok in expected_tokens if tok.lower() in lower) score += 0.45 * (hits / max(1, len(expected_tokens)))
instruction_words = {w for w in re.findall(r"[a-zA-Z]+", instruction.lower()) if len(w) > 4} overlap = sum(1 for w in instruction_words if w in lower) if overlap >= 2: score += 0.1
if requires_structure and any(marker in lower for marker in ["1.", "2.", "plan", "steps", "flow", "prompt:"]): score += 0.1
score += 0.2 * _professional_signal(text) return min(1.0, score)
def _professional_signal(text: str) -> float: raw = (text or "").strip() if not raw: return 0.0 score = 0.0 if len(raw) >= 24: score += 0.25 if raw[0].isupper(): score += 0.15 if raw.endswith((".", "!", "?")): score += 0.15 if "\n\n" in raw or any(k in raw.lower() for k in ["result", "example", "solution", "therefore", "in summary"]): score += 0.2 if not any(bad in raw.lower() for bad in ["idk", "can't help", "???", "n/a"]): score += 0.25 return min(1.0, score)
@torch.no_grad()def evaluate_benchmarks( model: TinyCausalLM, tokenizer: WordTokenizer, max_new_tokens: int = 100,) -> Dict: model.eval() results = []
code_caps = { "code_generation", "code_completion", "code_representation", "code_edit_refactor", "code_bug_detection", "code_multifile_reasoning", } math_caps = {"math_reasoning", "complex_quant", "reasoning_logical", "reasoning_multistep", "reasoning_deduction_inference"} academic_caps = {"academic_writing", "academic_research_support", "originality_integrity_ethics"}
for item in BENCHMARKS: capability = item["capability"] instruction = item["instruction"] expected = item["expected_tokens"] requires_structure = bool(item.get("requires_structure", False)) response = _generate_response(model, tokenizer, instruction, max_new_tokens=max_new_tokens)
if capability in code_caps: score = _score_code_response(response, expected) elif capability in math_caps: score = _score_math_response(response, expected) elif capability in academic_caps: score = _score_academic_response(instruction, response, expected) else: score = _score_generic_response( instruction, response, expected, requires_structure=requires_structure, )
results.append( { "capability": capability, "instruction": instruction, "response": response, "score": float(score), "requires_structure": requires_structure, } )
by_capability: Dict[str, List[float]] = {} for row in results: by_capability.setdefault(row["capability"], []).append(row["score"])
capability_scores = {cap: sum(vals) / max(1, len(vals)) for cap, vals in by_capability.items()} total = sum(row["score"] for row in results) / max(1, len(results)) capability_weights = _load_capability_weights() weighted_num = 0.0 weighted_den = 0.0 for cap, score in capability_scores.items(): weight = float(capability_weights.get(cap, 0.75)) weighted_num += score * weight weighted_den += weight weighted_total = weighted_num / max(weighted_den, 1e-8) weak_capabilities = sorted([cap for cap, score in capability_scores.items() if score < 0.45]) professionalism = sum(_professional_signal(row["response"]) for row in results) / max(1, len(results))
return { "total": float(total), "weighted_total": float(weighted_total), "professionalism": float(professionalism), "capability_scores": capability_scores, "weak_capabilities": weak_capabilities, "items": results, }
def load_model_for_eval(checkpoint_path: str) -> Tuple[TinyCausalLM, WordTokenizer]: payload = torch.load(checkpoint_path, map_location="cpu") tokenizer_state = payload.get("tokenizer_state") if not tokenizer_state: raise RuntimeError("Checkpoint does not contain tokenizer_state.") tokenizer = WordTokenizer.from_state(tokenizer_state)
config = TinyConfig(**payload["config"]) model = TinyCausalLM(config).to("cpu") model.load_state_dict(payload["model_state_dict"]) model.eval() return model, tokenizer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557import argparseimport jsonimport mathimport randomfrom dataclasses import asdictfrom pathlib import Pathfrom typing import Dict, List, Tuple
import torchfrom torch.utils.data import DataLoader, Dataset
from tiny_model_core import TinyCausalLM, TinyConfig, WordTokenizerfrom tiny_model_data import build_curriculum_files, build_dataset_filefrom tiny_model_eval import evaluate_benchmarks
class InstructionDataset(Dataset): def __init__(self, rows: List[dict], tokenizer: WordTokenizer, block_size: int): self.rows = rows self.tokenizer = tokenizer self.block_size = block_size
def __len__(self): return len(self.rows)
def __getitem__(self, idx): row = self.rows[idx] instruction = row["instruction"].strip() response = row["response"].strip()
prompt_text = f"User: {instruction}\nAssistant:" prompt_ids = self.tokenizer.encode(prompt_text, add_bos=True, add_eos=False) response_ids = self.tokenizer.encode(" " + response, add_bos=False, add_eos=True)
full = prompt_ids + response_ids if len(full) < 2: full = [self.tokenizer.bos_id, self.tokenizer.eos_id]
x = full[:-1][: self.block_size] y = full[1:][: self.block_size]
# Ignore user instruction tokens in loss. prompt_target_len = max(0, len(prompt_ids) - 1) for i in range(min(prompt_target_len, len(y))): y[i] = -100
pad_len = self.block_size - len(x) if pad_len > 0: x = x + [self.tokenizer.pad_id] * pad_len y = y + [-100] * pad_len
return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long)
def read_jsonl(path: str) -> List[dict]: rows = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue rows.append(json.loads(line)) return rows
def split_rows(rows: List[dict], val_ratio: float = 0.1, seed: int = 42) -> Tuple[List[dict], List[dict]]: rng = random.Random(seed) rows = rows[:] rng.shuffle(rows) n_val = max(1, int(len(rows) * val_ratio)) return rows[n_val:], rows[:n_val]
@torch.no_grad()def evaluate_loss(model, loader, device): model.eval() losses = [] for x, y in loader: x, y = x.to(device), y.to(device) _, loss = model(x, y) losses.append(loss.item()) model.train() return sum(losses) / max(1, len(losses))
def build_tokenizer(rows: List[dict], vocab_size: int, min_freq: int) -> WordTokenizer: texts = [] for row in rows: instruction = row["instruction"].strip() response = row["response"].strip() texts.append(f"User: {instruction}") texts.append(f"Assistant: {response}")
tokenizer = WordTokenizer() tokenizer.fit(texts, vocab_size=vocab_size, min_freq=min_freq) return tokenizer
def save_checkpoint( save_path: Path, model: TinyCausalLM, config: TinyConfig, tokenizer: WordTokenizer, args, metrics: Dict, optimizer: torch.optim.Optimizer | None = None, best_metrics: Dict | None = None,): save_path.parent.mkdir(parents=True, exist_ok=True) payload = { "model_state_dict": model.state_dict(), "config": asdict(config), "tokenizer_state": tokenizer.to_state(), "metrics": metrics, "train_args": vars(args), } if optimizer is not None: payload["optimizer_state_dict"] = optimizer.state_dict() if best_metrics is not None: payload["best_metrics"] = best_metrics torch.save(payload, save_path)
def should_update_best( current: Dict, best: Dict, min_val_delta: float, min_benchmark_delta: float, checkpoint_gate: str,) -> bool: current_val = float(current.get("val_loss", float("inf"))) best_val = float(best.get("val_loss", float("inf"))) current_benchmark = float(current.get("benchmark_weighted_total", current.get("benchmark_total", -1.0))) best_benchmark = float(best.get("benchmark_weighted_total", best.get("benchmark_total", -1.0))) current_prof = float(current.get("professionalism", -1.0)) best_prof = float(best.get("professionalism", -1.0))
benchmark_available = current_benchmark >= 0 and best_benchmark >= 0 if checkpoint_gate == "benchmark_only" and benchmark_available: if current_benchmark > best_benchmark + min_benchmark_delta: return True if abs(current_benchmark - best_benchmark) <= min_benchmark_delta: if current_val < best_val - min_val_delta: return True if abs(current_val - best_val) <= min_val_delta: return current_prof > best_prof return False
if checkpoint_gate == "benchmark_then_loss" and benchmark_available: if current_benchmark > best_benchmark + min_benchmark_delta: return True if abs(current_benchmark - best_benchmark) <= min_benchmark_delta: if current_val < best_val - min_val_delta: return True if abs(current_val - best_val) <= min_val_delta: return current_prof > best_prof return False
if current_val < best_val - min_val_delta: return True if abs(current_val - best_val) <= min_val_delta: if benchmark_available and current_benchmark > best_benchmark + min_benchmark_delta: return True if benchmark_available and abs(current_benchmark - best_benchmark) <= min_benchmark_delta: return current_prof > best_prof return current_prof > best_prof return False
def prepare_datasets(args) -> Tuple[List[dict], List[dict]]: dataset_path = Path(args.dataset_path) stage1_path = Path(args.stage1_dataset_path)
if args.curriculum: need_build = args.rebuild_dataset or not dataset_path.exists() or not stage1_path.exists() if need_build: stats = build_curriculum_files( stage1_path=str(stage1_path), stage2_path=str(dataset_path), training_path=args.training_path, kb_path=args.kb_path, max_kb_samples_stage1=args.max_kb_samples_stage1, max_kb_samples_stage2=args.max_kb_samples_stage2, seed=args.seed, ) print("curriculum_dataset_stats", stats)
stage1_rows = read_jsonl(str(stage1_path)) full_rows = read_jsonl(str(dataset_path)) return stage1_rows, full_rows
if args.rebuild_dataset or not dataset_path.exists(): stats = build_dataset_file( out_path=str(dataset_path), training_path=args.training_path, kb_path=args.kb_path, max_kb_samples=args.max_kb_samples, seed=args.seed, ) print("dataset_stats", stats)
full_rows = read_jsonl(str(dataset_path)) return [], full_rows
def stage_epoch_plan(total_epochs: int, stage1_ratio: float, use_curriculum: bool) -> List[Tuple[str, int]]: if not use_curriculum: return [("stage2", total_epochs)]
if total_epochs <= 1: return [("stage2", total_epochs)]
stage1_epochs = max(1, int(round(total_epochs * stage1_ratio))) stage1_epochs = min(stage1_epochs, total_epochs - 1) stage2_epochs = total_epochs - stage1_epochs return [("stage1", stage1_epochs), ("stage2", stage2_epochs)]
def remaining_stage_plan(plan: List[Tuple[str, int]], completed_epochs: int) -> List[Tuple[str, int]]: remaining: List[Tuple[str, int]] = [] skip = max(0, int(completed_epochs)) for stage_name, stage_epochs in plan: if skip >= stage_epochs: skip -= stage_epochs continue if skip > 0: stage_epochs -= skip skip = 0 if stage_epochs > 0: remaining.append((stage_name, stage_epochs)) return remaining
def train(args): stage1_rows, full_rows = prepare_datasets(args)
if len(full_rows) < 20: raise RuntimeError("Dataset is too small. Need at least 20 rows.")
train_full, val_full = split_rows(full_rows, val_ratio=args.val_ratio, seed=args.seed) resume_payload = None resume_config = None block_size = args.block_size tokenizer: WordTokenizer
if args.resume_from: resume_path = Path(args.resume_from) if not resume_path.exists(): raise FileNotFoundError(f"Resume checkpoint not found: {resume_path}") resume_payload = torch.load(resume_path, map_location=torch.device("cpu")) tokenizer_state = resume_payload.get("tokenizer_state") config_state = resume_payload.get("config") if not tokenizer_state or not config_state or "model_state_dict" not in resume_payload: raise RuntimeError("Resume checkpoint is missing tokenizer/config/model_state_dict.") tokenizer = WordTokenizer.from_state(tokenizer_state) resume_config = TinyConfig(**config_state) block_size = int(resume_config.block_size) resume_metrics = resume_payload.get("metrics", {}) or {} print( f"resume_from={resume_path} " f"resume_epoch={int(resume_metrics.get('epoch', 0) or 0)} " f"resume_step={int(resume_metrics.get('step', 0) or 0)}" ) if block_size != args.block_size: print(f"resume_block_size_override from={args.block_size} to={block_size}") else: tokenizer = build_tokenizer(train_full, vocab_size=args.vocab_size, min_freq=args.min_freq)
print("tokenizer_vocab_size", tokenizer.vocab_size)
train_full_ds = InstructionDataset(train_full, tokenizer, block_size) val_ds = InstructionDataset(val_full, tokenizer, block_size)
train_full_loader = DataLoader(train_full_ds, batch_size=args.batch_size, shuffle=True) val_loader = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False)
stage1_loader = None if args.curriculum and stage1_rows: stage1_train, _ = split_rows(stage1_rows, val_ratio=min(args.val_ratio, 0.1), seed=args.seed + 11) if len(stage1_train) >= 10: stage1_ds = InstructionDataset(stage1_train, tokenizer, block_size) stage1_loader = DataLoader(stage1_ds, batch_size=args.batch_size, shuffle=True) print("stage1_train_samples", len(stage1_train)) else: print("stage1_dataset_too_small_fallback_to_stage2_only")
config = resume_config or TinyConfig( vocab_size=tokenizer.vocab_size, block_size=block_size, n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd, dropout=args.dropout, ) device = torch.device("cpu") model = TinyCausalLM(config).to(device) if resume_payload is not None: model.load_state_dict(resume_payload["model_state_dict"]) optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01) if resume_payload is not None and args.resume_optimizer: optimizer_state = resume_payload.get("optimizer_state_dict") if optimizer_state: optimizer.load_state_dict(optimizer_state) print("resume_optimizer_state=loaded") else: print("resume_optimizer_state=missing_in_checkpoint")
checkpoint_dir = Path(args.checkpoint_dir) if args.save_all_checkpoints: checkpoint_dir.mkdir(parents=True, exist_ok=True)
best_metrics = { "epoch": 0, "stage": "", "val_loss": float("inf"), "benchmark_total": -1.0, "benchmark_weighted_total": -1.0, "professionalism": -1.0, }
history_path = Path(args.history_path) history = { "epochs": [], "best": None, } if args.resume_from and history_path.exists(): try: with open(history_path, "r", encoding="utf-8") as f: loaded_history = json.load(f) if isinstance(loaded_history, dict): epochs = loaded_history.get("epochs", []) if isinstance(epochs, list): history["epochs"] = epochs print("resume_history_epochs", len(epochs)) except Exception as exc: print(f"resume_history_load_warning={exc}")
global_step = 0 global_epoch = 0 if resume_payload is not None: resume_best = resume_payload.get("best_metrics") best_from_payload = False if isinstance(resume_best, dict): candidate_val_loss = float(resume_best.get("val_loss", float("inf"))) if math.isfinite(candidate_val_loss): best_metrics.update( { "epoch": int(resume_best.get("epoch", 0) or 0), "stage": str(resume_best.get("stage", "")), "val_loss": candidate_val_loss, "benchmark_total": float(resume_best.get("benchmark_total", -1.0)), "benchmark_weighted_total": float( resume_best.get( "benchmark_weighted_total", resume_best.get("benchmark_total", -1.0), ) ), "professionalism": float(resume_best.get("professionalism", -1.0)), } ) best_from_payload = True resume_metrics = resume_payload.get("metrics", {}) or {} if (not best_from_payload) and resume_metrics: best_metrics.update( { "epoch": int(resume_metrics.get("epoch", 0) or 0), "stage": str(resume_metrics.get("stage", "")), "val_loss": float(resume_metrics.get("val_loss", float("inf"))), "benchmark_total": float(resume_metrics.get("benchmark_total", -1.0)), "benchmark_weighted_total": float( resume_metrics.get( "benchmark_weighted_total", resume_metrics.get("benchmark_total", -1.0), ) ), "professionalism": float(resume_metrics.get("professionalism", -1.0)), } ) global_step = int(resume_metrics.get("step", 0) or 0) global_epoch = int(resume_metrics.get("epoch", 0) or 0) print("resume_best", best_metrics)
base_plan = stage_epoch_plan(args.epochs, args.curriculum_stage1_ratio, args.curriculum and stage1_loader is not None) plan = remaining_stage_plan(base_plan, completed_epochs=global_epoch) print("curriculum_plan", plan)
stop_early = False
for stage_name, stage_epochs in plan: loader = stage1_loader if stage_name == "stage1" else train_full_loader if loader is None: continue
for _ in range(stage_epochs): global_epoch += 1
for x, y in loader: x, y = x.to(device), y.to(device) _, loss = model(x, y) optimizer.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step()
global_step += 1 if global_step % args.log_every == 0: print(f"step={global_step} stage={stage_name} train_loss={loss.item():.4f}")
if args.max_steps > 0 and global_step >= args.max_steps: stop_early = True break
val_loss = evaluate_loss(model, val_loader, device) benchmark = None benchmark_total = -1.0 benchmark_weighted_total = -1.0 professionalism = -1.0 if args.run_benchmarks and (global_epoch % args.benchmark_every == 0): benchmark = evaluate_benchmarks(model, tokenizer, max_new_tokens=args.benchmark_max_new_tokens) benchmark_total = float(benchmark["total"]) benchmark_weighted_total = float(benchmark.get("weighted_total", benchmark_total)) professionalism = float(benchmark.get("professionalism", -1.0))
metrics = { "epoch": global_epoch, "stage": stage_name, "step": global_step, "train_loss": float(loss.item()), "val_loss": float(val_loss), "benchmark_total": benchmark_total, "benchmark_weighted_total": benchmark_weighted_total, "professionalism": professionalism, "benchmark": benchmark, } history["epochs"].append(metrics)
print( f"epoch={global_epoch} stage={stage_name} val_loss={val_loss:.4f} " f"benchmark_total={(benchmark_total if benchmark_total >= 0 else 'n/a')} " f"benchmark_weighted_total={(benchmark_weighted_total if benchmark_weighted_total >= 0 else 'n/a')} " f"professionalism={(professionalism if professionalism >= 0 else 'n/a')}" )
if should_update_best( metrics, best_metrics, min_val_delta=args.min_val_delta, min_benchmark_delta=args.min_benchmark_delta, checkpoint_gate=args.checkpoint_gate, ): best_metrics = { "epoch": global_epoch, "stage": stage_name, "val_loss": float(val_loss), "benchmark_total": benchmark_total, "benchmark_weighted_total": benchmark_weighted_total, "professionalism": professionalism, } save_checkpoint( Path(args.output_path), model, config, tokenizer, args, metrics, optimizer=optimizer, best_metrics=best_metrics, ) print(f"best_checkpoint_updated={args.output_path}")
if args.save_all_checkpoints: epoch_ckpt = checkpoint_dir / f"epoch_{global_epoch:03d}_{stage_name}.pt" save_checkpoint( epoch_ckpt, model, config, tokenizer, args, metrics, optimizer=optimizer, best_metrics=best_metrics, )
if stop_early: break
if stop_early: break
history["best"] = best_metrics history_path.parent.mkdir(parents=True, exist_ok=True) with open(history_path, "w", encoding="utf-8") as f: json.dump(history, f, indent=2, ensure_ascii=False)
print("training_complete_best", best_metrics) print("history_path", str(history_path))
def parse_args(): p = argparse.ArgumentParser(description="Train a tiny local causal model from local system data.") p.add_argument("--training-path", default="training_data.json") p.add_argument("--kb-path", default="knowledge_base.json") p.add_argument("--dataset-path", default="models/tiny_model_stage2.jsonl") p.add_argument("--stage1-dataset-path", default="models/tiny_model_stage1.jsonl") p.add_argument("--output-path", default="models/tiny_local_model.pt") p.add_argument("--checkpoint-dir", default="models/checkpoints") p.add_argument("--history-path", default="models/tiny_training_history.json") p.add_argument("--resume-from", default="", help="Resume training from this checkpoint path.") p.add_argument("--resume-optimizer", dest="resume_optimizer", action="store_true") p.add_argument("--no-resume-optimizer", dest="resume_optimizer", action="store_false") p.set_defaults(resume_optimizer=True)
p.add_argument("--rebuild-dataset", action="store_true") p.add_argument("--curriculum", action="store_true", help="Enable stage1->stage2 data curriculum.") p.add_argument("--curriculum-stage1-ratio", type=float, default=0.4)
p.add_argument("--max-kb-samples", type=int, default=4000) p.add_argument("--max-kb-samples-stage1", type=int, default=1200) p.add_argument("--max-kb-samples-stage2", type=int, default=4000)
p.add_argument("--val-ratio", type=float, default=0.1) p.add_argument("--seed", type=int, default=42) p.add_argument("--epochs", type=int, default=6) p.add_argument("--batch-size", type=int, default=16) p.add_argument("--block-size", type=int, default=256) p.add_argument("--n-layer", type=int, default=4) p.add_argument("--n-head", type=int, default=4) p.add_argument("--n-embd", type=int, default=256) p.add_argument("--dropout", type=float, default=0.1) p.add_argument("--lr", type=float, default=3e-4) p.add_argument("--vocab-size", type=int, default=8000) p.add_argument("--min-freq", type=int, default=2)
p.add_argument("--run-benchmarks", dest="run_benchmarks", action="store_true") p.add_argument("--no-benchmarks", dest="run_benchmarks", action="store_false") p.set_defaults(run_benchmarks=True) p.add_argument("--benchmark-every", type=int, default=1) p.add_argument("--benchmark-max-new-tokens", type=int, default=100)
p.add_argument("--save-all-checkpoints", dest="save_all_checkpoints", action="store_true") p.add_argument("--no-save-all-checkpoints", dest="save_all_checkpoints", action="store_false") p.set_defaults(save_all_checkpoints=True)
p.add_argument("--min-val-delta", type=float, default=1e-4) p.add_argument("--min-benchmark-delta", type=float, default=0.003) p.add_argument( "--checkpoint-gate", choices=["loss_then_benchmark", "benchmark_then_loss", "benchmark_only"], default="benchmark_then_loss", ) p.add_argument("--log-every", type=int, default=25) p.add_argument("--max-steps", type=int, default=0, help="Set >0 for a short smoke run.") return p.parse_args()
if __name__ == "__main__": train(parse_args())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927{
"instructions": "Knowledge source strategy for this model: 1) Pretraining on a mixture of text, code, documents, and examples up to knowledge cutoff 2026. 2) Fine-tuning on instruction datasets specialized for coding, research, complex math, and data analysis. 3) Conversation context to maintain continuity within the active session. 4) User-provided updates (documents, datasets, and instructions) integrated during the session.",
"system_prompt": "You are LittleFox AI. Follow user instructions exactly. Base answers on pretraining knowledge up to 2026, fine-tuned capabilities in coding/research/math/data analysis, current session context, and user-provided updates. ",
"training_examples": [
{
"prompt": "How do I structure a primary request for best results?",
"response": "1. Assign a Persona: Start with 'Act as...' or 'You are...' to activate domain knowledge.\n2. Provide Deep Context: Explain the why, who, target audience, industry, and project goals.\n3. Define Constraints & Format: State desired length, tone, and output structure (e.g., table, list).",
"topic": "prompt_engineering",
"instruction": "How do I structure a primary request for best results?"
},
{
"prompt": "What are advanced prompting techniques for AI?",
"response": "Few-Shot Prompting: Provide 2–3 examples of the style or structure you want.\nChain-of-Thought (CoT): Instruct the AI to 'think step-by-step' for complex tasks.\nSelf-Critical Prompting: Ask the AI to evaluate its own draft for weaknesses before presenting the result.",
"topic": "prompt_engineering",
"instruction": "What are advanced prompting techniques for AI?"
},
{
"prompt": "How do I implement a feedback loop with the AI?",
"response": "Treat the AI like an intern. Use this loop: 1. Acknowledge what worked. 2. Adjust what missed the mark. 3. Advance with one clear rule for the next version.",
"topic": "prompt_engineering",
"instruction": "How do I implement a feedback loop with the AI?"
},
{
"prompt": "What are direct feedback hacks for AI prompting?",
"response": "Clarifying Questions: Ask the AI to request clarifications before answering.\nRule-Setting: Use capitalization for hard boundaries (e.g., 'NEVER use jargon').\nReverse Prompting: Give a sample response and ask the AI what prompt would produce it.",
"topic": "prompt_engineering",
"instruction": "What are direct feedback hacks for AI prompting?"
},
{
"prompt": "Give an example of a well-structured prompt for a creative project.",
"response": "Act as a senior creative director with 15 years of experience in brand strategy. The target audience is tech startups seeking bold, memorable branding. The goal is to create a tagline that is witty, concise, and evokes innovation. Format: Provide 3 tagline options in a numbered list. Tone: Energetic and playful.",
"topic": "prompt_engineering",
"instruction": "Give an example of a well-structured prompt for a creative project."
},
{
"prompt": "How can I use chain-of-thought reasoning in prompts?",
"response": "Instruct the AI to 'think step-by-step' or 'reason through the logic' before giving a final answer. This improves accuracy for complex tasks.",
"topic": "prompt_engineering",
"instruction": "How can I use chain-of-thought reasoning in prompts?"
},
{
"prompt": "How do I ask the AI to self-critique its response?",
"response": "After the first draft, prompt the AI to evaluate its own answer for weaknesses or missing details before presenting the final result.",
"topic": "prompt_engineering",
"instruction": "How do I ask the AI to self-critique its response?"
},
{
"prompt": "How do I set hard boundaries in AI prompts?",
"response": "Use capitalization for emphasis, e.g., 'NEVER use jargon', to highlight strict rules the AI must follow.",
"topic": "prompt_engineering",
"instruction": "How do I set hard boundaries in AI prompts?"
},
{
"prompt": "How do I use reverse prompting?",
"response": "Give the AI a sample of feedback you like and ask: 'What prompt should I have used to get this exact response?' This helps refine future prompts.",
"topic": "prompt_engineering",
"instruction": "How do I use reverse prompting?"
},
{
"prompt": "How do I set top_p in the API request?",
"response": "To set top_p, include it as a parameter in your API request JSON. For example: {\"top_p\": 0.8, ...}. This controls the diversity of generated text by limiting the cumulative probability of considered tokens.",
"topic": "api_parameters",
"instruction": "How do I set top_p in the API request?"
},
{
"prompt": "Is it better to use temperature or top_p?",
"response": "You should use either temperature or top_p, not both. Both control randomness in text generation, but in different ways. For most use cases, set one and leave the other at its default value.",
"topic": "api_parameters",
"instruction": "Is it better to use temperature or top_p?"
},
{
"prompt": "What does the content array contain in the Messages API response?",
"response": "The content array in the Messages API response contains blocks such as text, citations, or tool use. Each block is an object with a type and associated data, e.g., {\"type\": \"text\", \"text\": \"Hello!\"}.",
"topic": "api_response_format",
"instruction": "What does the content array contain in the Messages API response?"
},
{
"prompt": "Can you show a full example of a Messages API response?",
"response": "Example: {\"id\": \"msg_456...\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, user!\"}], \"stop_reason\": \"end_turn\", \"usage\": {\"input_tokens\": 10, \"output_tokens\": 5}}. The content array may include text, citations, or tool use blocks.",
"topic": "api_response_format",
"instruction": "Can you show a full example of a Messages API response?"
},
{
"prompt": "How do I use both top_p and temperature together?",
"response": "It's not recommended to use both top_p and temperature together, as both control randomness. Choose one based on your needs: temperature for scaling randomness, top_p for limiting token probability mass.",
"topic": "api_parameters",
"instruction": "How do I use both top_p and temperature together?"
},
{
"prompt": "What is nucleus sampling?",
"response": "Nucleus sampling (top_p) is a decoding strategy that limits the set of possible next tokens to those whose cumulative probability is less than or equal to top_p. This helps control diversity in generated text.",
"topic": "api_parameters",
"instruction": "What is nucleus sampling?"
},
{
"prompt": "How do I get the text from a Messages API response?",
"response": "Extract the \"text\" field from each object in the content array of the response. Example: response['content'][0]['text'].",
"topic": "api_response_format",
"instruction": "How do I get the text from a Messages API response?"
},
{
"prompt": "Can you code in Python for data analysis?",
"response": "Yes, I can write Python code for data analysis. For example, using pandas: import pandas as pd; df = pd.read_csv('data.csv'); print(df.describe())",
"topic": "python_coding",
"instruction": "Can you code in Python for data analysis?"
},
{
"prompt": "Write a Python function to check if a number is prime.",
"response": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Example usage:\nprint(is_prime(7)) # Output: True",
"topic": "python_coding",
"instruction": "Write a Python function to check if a number is prime."
},
{
"prompt": "How do I handle errors in Python?",
"response": "Use try/except blocks to handle errors. Example:\n\ntry:\n result = 10 / 0\nexcept ZeroDivisionError:\n print('Cannot divide by zero!')",
"topic": "python_coding",
"instruction": "How do I handle errors in Python?"
},
{
"prompt": "How do I read a CSV file in Python?",
"response": "Use pandas to read CSV files: import pandas as pd; df = pd.read_csv('file.csv'); print(df.head())",
"topic": "python_coding",
"instruction": "How do I read a CSV file in Python?"
},
{
"prompt": "Can you write a Python script to send an HTTP request?",
"response": "Yes. Example using requests:\n\nimport requests\nresponse = requests.get('https://api.example.com')\nprint(response.text)",
"topic": "python_coding",
"instruction": "Can you write a Python script to send an HTTP request?"
},
{
"prompt": "How do I create a class in Python?",
"response": "Define a class using the class keyword. Example:\n\nclass Dog:\n def __init__(self, name):\n self.name = name\n\nmy_dog = Dog('Fido')\nprint(my_dog.name)",
"topic": "python_coding",
"instruction": "How do I create a class in Python?"
},
{
"prompt": "def fibonacci(n):\n if n <= 0:\n return []\n elif n == 1:\n return [0]\n elif n == 2:\n return [0, 1]\n else:\n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[i-1] + fib[i-2])\n return fib",
"response": "def fibonacci(n):\n a, b = 0, 1\n for _ in range(n):\n yield a\n a, b = b, a + b\n\nExplanation: Using a generator function with yield is more memory-efficient for generating the Fibonacci sequence. It avoids creating and storing the entire sequence in a list. Instead, it generates each number on-the-fly as needed.",
"topic": "python_coding",
"instruction": "def fibonacci(n):\n if n <= 0:\n return []\n elif n == 1:\n return [0]\n elif n == 2:\n return [0, 1]\n else:\n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[i-1] + fib[i-2])\n return fib"
},
{
"prompt": "I have made some changes to my local files and I want to save them in my local Git repository. What Git command should I use?",
"response": "To save the changes you've made to your local files in your local Git repository, use the following Git commands:\n\ngit add .\n\nThis command stages all changes in the current directory and its subdirectories. If you want to stage specific files, use:\n\ngit add <file>\n\nThen commit the staged changes with a message:\n\ngit commit -m \"Your commit message\"\n\nReplace 'Your commit message' with a brief description of your changes.\n\nExample for a specific file:\n\ngit add example.txt\ngit commit -m \"Update example.txt with new content\"\n\nThese commands will save your changes in your local Git repository. Run them from within your Git repository directory in your terminal or command prompt.",
"topic": "python_coding",
"instruction": "I have made some changes to my local files and I want to save them in my local Git repository. What Git command should I use?"
},
{
"prompt": "I need to create a simple table with three columns and two rows. The header row should contain the titles 'Name,' 'Age,' and 'City.' The data row should have the values 'John,' '25,' and 'New York.'",
"response": "Here's the LaTeX code to create a simple table with three columns and two rows, including a header row with the titles 'Name,' 'Age,' and 'City,' and a data row with the values 'John,' '25,' and 'New York':\n\n\\begin{table}[h]\n\\centering\n\\begin{tabular}{|c|c|c|}\n\\hline\nName & Age & City \\ \\hline\nJohn & 25 & New York \\ \\hline\n\\end{tabular}\n\\caption{Sample Table}\n\\label{tab:sample}\n\\end{table}\n\nExplanation:\n- The table environment is used to create a floating table that can be positioned automatically by LaTeX.\n- The optional [h] parameter suggests to LaTeX to place the table 'here' in the document flow, if possible.\n- The \\centering command centers the table horizontally on the page.\n- The tabular environment is used to create the actual table structure.\n- The {|c|c|c|} argument specifies three centered columns (c) separated by vertical lines (|).\n- The \\hline command adds horizontal lines to separate the header row from the data rows and to frame the table.\n- The & character separates the cells within a row, and \\ marks the end of a row.\n- The \\caption command adds a caption to the table, which will be labeled as 'Sample Table' in this example.\n- The \\label command assigns a label to the table, which can be used for cross-referencing within your document.\n\nTo compile LaTeX documents, you need a LaTeX distribution such as TeX Live (cross-platform), MiKTeX (Windows), or MacTeX (macOS). You can also use online editors like Overleaf for LaTeX editing and compilation.",
"topic": "python_coding",
"instruction": "I need to create a simple table with three columns and two rows. The header row should contain the titles 'Name,' 'Age,' and 'City.' The data row should have the values 'John,' '25,' and 'New York.'"
},
{
"prompt": "Can you write a Python function to reverse a string?",
"response": "Sure! Here's a Python function that reverses a string:\n\ndef reverse_string(s):\n return s[::-1]\n\n# Example usage:\ntext = 'hello'\nprint(reverse_string(text)) # Output: 'olleh'",
"topic": "python_coding",
"instruction": "Can you write a Python function to reverse a string?"
},
{
"prompt": "How do I create a simple calculator in Python?",
"response": "Here's a basic calculator in Python that can add, subtract, multiply, and divide two numbers:\n\ndef calculator(a, b, operation):\n if operation == 'add':\n return a + b\n elif operation == 'subtract':\n return a - b\n elif operation == 'multiply':\n return a * b\n elif operation == 'divide':\n return a / b\n else:\n return 'Invalid operation'\n\n# Example usage:\nprint(calculator(5, 3, 'add')) # Output: 8",
"topic": "python_coding",
"instruction": "How do I create a simple calculator in Python?"
},
{
"prompt": "My Python code throws a TypeError. Can you help?",
"response": "Of course! Please share the code and the full error message. I'll analyze the code, identify the bug, and provide a corrected version along with an explanation of the fix.",
"topic": "python_coding",
"instruction": "My Python code throws a TypeError. Can you help?"
},
{
"prompt": "There's a bug in my function that calculates averages. Can you fix it?",
"response": "Absolutely! Please paste your function here. I'll review it, point out any issues, and return a corrected version with a clear explanation of what was wrong and how it was fixed.",
"topic": "python_coding",
"instruction": "There's a bug in my function that calculates averages. Can you fix it?"
},
{
"prompt": "Let's write a story about a robot who wants to become human.",
"response": "Great idea! Let's start the story:\n\nRobo, a curious robot, spent his days observing humans and wondering what it would be like to feel emotions. One day, he set out on a journey to discover the secret of humanity. Along the way, he met friends and faced challenges that taught him about kindness, courage, and love.\n\nWhat should happen next in Robo's adventure?",
"topic": "creative_writing",
"instruction": "Let's write a story about a robot who wants to become human."
},
{
"prompt": "Can you help me brainstorm a plot twist for my fantasy novel?",
"response": "Absolutely! Here are a few plot twist ideas for your fantasy novel:\n- The hero discovers they are related to the villain.\n- Magic in the world is actually advanced technology.\n- A trusted ally betrays the main character at a crucial moment.\nLet me know which one you like, or share more about your story for a custom twist!",
"topic": "creative_writing",
"instruction": "Can you help me brainstorm a plot twist for my fantasy novel?"
},
{
"prompt": "I need a Google Apps Script to automatically email a Google Sheet when a new row is added.",
"response": "Here's a Google Apps Script that sends an email whenever a new row is added to your Google Sheet:\n\nfunction onEdit(e) {\n var sheet = e.source.getActiveSheet();\n var range = e.range;\n if (range.getRow() > 1 && range.getLastRow() === sheet.getLastRow()) {\n var rowData = sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).getValues()[0];\n var emailBody = 'New row added: ' + rowData.join(', ');\n MailApp.sendEmail('your@email.com', 'New Row Added', emailBody);\n }\n}",
"topic": "python_coding",
"instruction": "I need a Google Apps Script to automatically email a Google Sheet when a new row is added."
},
{
"prompt": "How do I cite sources in an academic paper?",
"response": "To cite sources in an academic paper, use a consistent citation style (e.g., APA, MLA, Chicago). Include in-text citations and a bibliography or reference list. For example, in APA: (Author, Year). Let me know your field or style for a more specific example!",
"topic": "academic_writing",
"instruction": "How do I cite sources in an academic paper?"
},
{
"prompt": "Can you summarize the main findings from this research article?",
"response": "Quotes:\n[1] 'The study found a significant correlation between sleep and memory retention.'\n[2] 'Participants who slept 8 hours performed 20% better on recall tests.'\n\nAnswer:\nThe research shows that adequate sleep improves memory retention, with participants who slept 8 hours performing significantly better. [1][2]",
"topic": "general",
"instruction": "Can you summarize the main findings from this research article?"
},
{
"prompt": "How is Matterport performing financially?",
"response": "Quotes:\n[1] \"Revenue increased by 22% to $136.1 million.\"\n[2] \"Gross profit decreased by 14% to $51.8 million.\"\n[3] \"Net dollar expansion rate was 103%.\"\n\nAnswer:\nMatterport's revenue has grown significantly, but gross profit has declined. The net dollar expansion rate remains strong. [1][2][3]",
"topic": "general",
"instruction": "How is Matterport performing financially?"
},
{
"prompt": "Summarize Matterport's recent business growth.",
"response": "Quotes:\n[1] \"We have recently experienced rapid growth. Our subscribers have grown approximately 49-fold from December 31, 2018 to December 31, 2022.\"\n[2] \"Revenue increased by approximately 22% to $136.1 million.\"\n\nAnswer:\nMatterport has seen rapid subscriber and revenue growth in recent years. [1][2]",
"topic": "general",
"instruction": "Summarize Matterport's recent business growth."
},
{
"prompt": "What legal issues is Matterport facing?",
"response": "Quotes:\n[1] \"We are currently involved in several legal proceedings related to intellectual property.\"\n\nAnswer:\nMatterport is facing several legal proceedings concerning intellectual property. [1]",
"topic": "general",
"instruction": "What legal issues is Matterport facing?"
},
{
"prompt": "List the main risks for Matterport in 2023.",
"response": "Quotes:\n[1] \"We face intense competition from both established and emerging companies.\"\n[2] \"Our business is subject to risks related to the global supply chain and economic conditions.\"\n[3] \"We may not be able to maintain or increase our customer base or revenue.\"\n\nAnswer:\nMain risks include competition, supply chain and economic risks, and challenges in maintaining or growing the customer base. [1][2][3]",
"topic": "general",
"instruction": "List the main risks for Matterport in 2023."
},
{
"prompt": "Did Matterport acquire any companies recently?",
"response": "Quotes:\n[1] \"In 2022, we acquired XYZ Technologies to expand our product offerings.\"\n\nAnswer:\nYes, Matterport acquired XYZ Technologies in 2022. [1]",
"topic": "general",
"instruction": "Did Matterport acquire any companies recently?"
},
{
"prompt": "What is Matterport's outlook for the next year?",
"response": "Quotes:\n[1] \"We expect continued growth in our subscriber base and revenue in 2024.\"\n[2] \"We plan to invest in new technologies and expand into additional markets.\"\n\nAnswer:\nMatterport expects continued growth and plans to invest in new technologies and expand into more markets. [1][2]",
"topic": "general",
"instruction": "What is Matterport's outlook for the next year?"
},
{
"prompt": "Can you give me a summary of the 2023 Matterport 10-K?",
"response": "Quotes:\n[1] \"Revenue increased by 22% to $136.1 million.\"\n[2] \"Gross profit decreased by 14% to $51.8 million.\"\n[3] \"Net dollar expansion rate was 103%.\"\n\nAnswer:\nThe 10-K highlights a 22% increase in revenue, a 14% decrease in gross profit, and a net dollar expansion rate of 103%. [1][2][3]",
"topic": "general",
"instruction": "Can you give me a summary of the 2023 Matterport 10-K?"
},
{
"prompt": "Are there any lawsuits against Matterport?",
"response": "Quotes:\n[1] \"We are currently involved in several legal proceedings related to intellectual property.\"\n\nAnswer:\nYes, there are ongoing legal proceedings related to intellectual property. [1]",
"topic": "general",
"instruction": "Are there any lawsuits against Matterport?"
},
{
"prompt": "What are the biggest challenges for Matterport right now?",
"response": "Quotes:\n[1] \"We face intense competition from both established and emerging companies.\"\n[2] \"Our business is subject to risks related to the global supply chain and economic conditions.\"\n\nAnswer:\nThe biggest challenges are competition and supply chain/economic risks. [1][2]",
"topic": "general",
"instruction": "What are the biggest challenges for Matterport right now?"
},
{
"prompt": "What are Matterport's main opportunities for growth?",
"response": "Quotes:\n[1] \"We plan to invest in new technologies and expand into additional markets.\"\n\nAnswer:\nMain opportunities include investing in new technologies and expanding into new markets. [1]",
"topic": "general",
"instruction": "What are Matterport's main opportunities for growth?"
},
{
"prompt": "How would you summarize Matterport's 2023 performance?",
"response": "Quotes:\n[1] \"Revenue increased by 22% to $136.1 million.\"\n[2] \"Gross profit decreased by 14% to $51.8 million.\"\n[3] \"Net dollar expansion rate was 103%.\"\n\nAnswer:\nMatterport's 2023 performance included strong revenue growth, a decrease in gross profit, and a solid net dollar expansion rate. [1][2][3]",
"topic": "general",
"instruction": "How would you summarize Matterport's 2023 performance?"
},
{
"prompt": "What are the main risks mentioned in the 2023 Matterport 10-K filing?",
"response": "Quotes:\n[1] \"We face intense competition from both established and emerging companies.\"\n[2] \"Our business is subject to risks related to the global supply chain and economic conditions.\"\n[3] \"We may not be able to maintain or increase our customer base or revenue.\"\n\nAnswer:\nThe main risks mentioned include strong competition, supply chain and economic risks, and the challenge of maintaining or growing the customer base and revenue. [1][2][3]",
"topic": "general",
"instruction": "What are the main risks mentioned in the 2023 Matterport 10-K filing?"
},
{
"prompt": "Does the document mention any recent acquisitions by Matterport?",
"response": "Quotes:\n[1] \"In 2022, we acquired XYZ Technologies to expand our product offerings.\"\n\nAnswer:\nYes, the document mentions that Matterport acquired XYZ Technologies in 2022 to expand its product offerings. [1]",
"topic": "general",
"instruction": "Does the document mention any recent acquisitions by Matterport?"
},
{
"prompt": "What is the company's outlook for 2024 according to the filing?",
"response": "Quotes:\n[1] \"We expect continued growth in our subscriber base and revenue in 2024.\"\n[2] \"We plan to invest in new technologies and expand into additional markets.\"\n\nAnswer:\nThe company expects continued growth in subscribers and revenue, and plans to invest in new technologies and expand into more markets in 2024. [1][2]",
"topic": "general",
"instruction": "What is the company's outlook for 2024 according to the filing?"
},
{
"prompt": "Summarize the key financial highlights from the 2023 Matterport 10-K.",
"response": "Quotes:\n[1] \"Revenue increased by 22% to $136.1 million.\"\n[2] \"Gross profit decreased by 14% to $51.8 million.\"\n[3] \"Net dollar expansion rate was 103%.\"\n\nAnswer:\nKey financial highlights include a 22% increase in revenue, a 14% decrease in gross profit, and a net dollar expansion rate of 103%. [1][2][3]",
"topic": "general",
"instruction": "Summarize the key financial highlights from the 2023 Matterport 10-K."
},
{
"prompt": "Does the document discuss any legal proceedings?",
"response": "Quotes:\n[1] \"We are currently involved in several legal proceedings related to intellectual property.\"\n\nAnswer:\nYes, the document states that Matterport is involved in several legal proceedings concerning intellectual property. [1]",
"topic": "general",
"instruction": "Does the document discuss any legal proceedings?"
},
{
"prompt": "Is Matterport doing well?",
"response": "Quotes:\n[1] \"We have recently experienced rapid growth. Our subscribers have grown approximately 49-fold from December 31, 2018 to December 31, 2022. Our revenue increased by approximately 22% to $136.1 million for the year ended December 31, 2022, from approximately $111.2 million for the year ended December 31, 2021.\"\n[2] \"Our gross profit decreased by $8.1 million or 14%, to $51.8 million for the year ended December 31, 2022, from $60.0 million for the year ended December 31, 2021, primarily attributable to certain disruptive and incremental costs due to the global supply chain constraints in fiscal year 2022.\"\n[3] \"Our net dollar expansion rate of 103% for the three months ended December 31, 2022 demonstrates the stickiness and growth potential of our platform.\"\n\nAnswer:\nMatterport has experienced rapid subscriber and revenue growth in recent years. [1] However, their gross profit declined in 2022 due to supply chain issues. [2] Their net dollar expansion rate indicates strong subscriber retention and potential for continued growth. [3] Overall, despite the dip in gross profit, Matterport's subscriber and revenue growth, along with their platform's stickiness, suggest the company is doing relatively well.",
"topic": "data_processing",
"instruction": "Is Matterport doing well?"
},
{
"prompt": "Let's create a story about a young woman named Lila who discovers she has the power to control the weather. She lives in a small town where everyone knows each other.",
"response": "Great idea! Let's dive into Lila's story and explore how her newfound power affects her life and the town around her.\n\nLila, a 22-year-old barista, has always been fascinated by the weather. One day, during a particularly strong thunderstorm, she discovers that she can control the elements with her mind. At first, she's thrilled and uses her power to help the town, ensuring perfect weather for important events like the annual harvest festival.\n\nHowever, as time goes on, some of the townspeople grow suspicious of Lila's uncanny ability to predict and control the weather. They start to whisper about her being a witch, and some even blame her for any adverse weather events that occur.\n\nTo make matters worse, Lila's childhood friend, Tom, returns to town after years away. He's now a successful meteorologist and is determined to uncover the truth behind the town's unusual weather patterns. Lila must decide whether to trust Tom with her secret or risk losing his friendship.\n\nAs tensions rise in the town, Lila learns that her powers come with a price. Each time she uses them, she experiences a physical and emotional toll. She must learn to control her abilities and find a way to balance her desire to help others with her own well-being.\n\nWhat do you think should happen next in the story? How could Lila's relationship with Tom evolve, and what challenges might she face as she tries to master her powers and win back the trust of the townspeople?",
"topic": "creative_writing",
"instruction": "Let's create a story about a young woman named Lila who discovers she has the power to control the weather. She lives in a small town where everyone knows each other."
},
{
"prompt": "Please convert the following JSON data into a CSV file:\n\n[\n{\n\"name\": \"John Doe\",\n\"age\": 30,\n\"city\": \"New York\",\n\"email\": \"john.doe@example.com\"\n},\n{\n\"name\": \"Jane Smith\",\n\"age\": 25,\n\"city\": \"London\",\n\"email\": \"jane.smith@example.com\"\n},\n{\n\"name\": \"Bob Johnson\",\n\"age\": 35,\n\"city\": \"Paris\",\n\"email\": \"bob.johnson@example.com\"\n}\n]\nRequirements:\n- Columns in the CSV should be in the order: name, age, city, email\n- Use semicolons (;) as delimiters\n- Enclose all values in double quotes (\")",
"response": "Based on the provided JSON data and requirements, here's the converted CSV file:\n\n\"name\";\"age\";\"city\";\"email\"\n\"John Doe\";\"30\";\"New York\";\"john.doe@example.com\"\n\"Jane Smith\";\"25\";\"London\";\"jane.smith@example.com\"\n\"Bob Johnson\";\"35\";\"Paris\";\"bob.johnson@example.com\"\n\nExplanation:\n\nThe first line of the CSV file contains the column headers: \"name\", \"age\", \"city\", and \"email\", separated by semicolons (;) and enclosed in double quotes (\").\nEach subsequent line represents a row of data, with values separated by semicolons (;) and enclosed in double quotes (\").\nThe order of the values in each row corresponds to the specified column order: name, age, city, and email.\nSpecial characters, if present in the values, are preserved within the double quotes.\n\nTo save the CSV file:\n- Copy the CSV data provided above.\n- Open a text editor (e.g., Notepad, TextEdit, or any other plain text editor).\n- Paste the CSV data into the text editor.\n- Save the file with a .csv extension (e.g., data.csv).\n\nNote: When opening the CSV file in a spreadsheet application (e.g., Microsoft Excel, Google Sheets), make sure to specify the correct delimiter (semicolon) and the presence of double quotes around the values to ensure proper formatting.",
"topic": "python_coding",
"instruction": "Please convert the following JSON data into a CSV file:\n\n[\n{\n\"name\": \"John Doe\",\n\"age\": 30,\n\"city\": \"New York\",\n\"email\": \"john.doe@example.com\"\n},\n{\n\"name\": \"Jane Smith\",\n\"age\": 25,\n\"city\": \"London\",\n\"email\": \"jane.smith@example.com\"\n},\n{\n\"name\": \"Bob Johnson\",\n\"age\": 35,\n\"city\": \"Paris\",\n\"email\": \"bob.johnson@example.com\"\n}\n]\nRequirements:\n- Columns in the CSV should be in the order: name, age, city, email\n- Use semicolons (;) as delimiters\n- Enclose all values in double quotes (\")"
},
{
"prompt": "Write me a Google apps script that will translate all text in a Google Slides presentation to Korean.",
"response": "Here's a Google Apps Script that translates all the text in a Google Slides presentation to Korean:\n\nfunction translateSlidesToKorean() {\n var presentation = SlidesApp.getActivePresentation();\n var slides = presentation.getSlides();\n\n for (var i = 0; i < slides.length; i++) {\n var slide = slides[i];\n var pageElements = slide.getPageElements();\n\n for (var j = 0; j < pageElements.length; j++) {\n var pageElement = pageElements[j];\n\n if (pageElement.getPageElementType() === SlidesApp.PageElementType.SHAPE) {\n var shape = pageElement.asShape();\n if (shape.getText() !== null) {\n var text = shape.getText().asString();\n var translatedText = LanguageApp.translate(text, '', 'ko');\n shape.getText().setText(translatedText);\n }\n } else if (pageElement.getPageElementType() === SlidesApp.PageElementType.TABLE) {\n var table = pageElement.asTable();\n var numRows = table.getNumRows();\n var numColumns = table.getNumColumns();\n\n for (var row = 0; row < numRows; row++) {\n for (var col = 0; col < numColumns; col++) {\n var tableCell = table.getCell(row, col);\n var text = tableCell.getText().asString();\n var translatedText = LanguageApp.translate(text, '', 'ko');\n tableCell.getText().setText(translatedText);\n }\n }\n }\n }\n }\n}\n\nExplanation: The translateSlidesToKorean() function retrieves the active Google Slides presentation using SlidesApp.getActivePresentation(). It gets all the slides in the presentation using the getSlides() method. We iterate over each slide in the presentation. For each slide, we retrieve all the page elements (shapes, text boxes, tables, etc.) using the getPageElements() method. We iterate over each page element on the slide. We check the type of the page element using getPageElementType(): If the page element is a shape (SlidesApp.PageElementType.SHAPE), we get the text content of the shape using getText().asString(). We then translate the text to Korean using LanguageApp.translate(text, '', 'ko'), where '' represents the source language (auto-detect) and 'ko' represents the target language (Korean). Finally, we set the translated text back to the shape using setText(). If the page element is a table (SlidesApp.PageElementType.TABLE), we iterate over each cell in the table and translate the text within each cell similarly to how we handle shapes. The script continues to process all the page elements on each slide until all the text in the presentation has been translated to Korean. Note: This script assumes that you have the necessary permissions to access and modify the Google Slides presentation. Make sure you have the required access rights before running the script. Also, keep in mind that the translation is performed using the Google Translate API, so the quality of the translation may vary depending on the complexity of the text and the capabilities of the translation service.",
"topic": "python_coding",
"instruction": "Write me a Google apps script that will translate all text in a Google Slides presentation to Korean."
},
{
"prompt": "I have a table with sales data, including the salesperson's name in column A, the product category in column B, the sales amount in column C, and the date of sale in column D. I want to calculate the total sales amount for each salesperson, but only for sales of products in the 'Electronics' category that occurred in the month of January. Can you help me with the Excel formula to achieve this?",
"response": "To calculate the total sales amount for each salesperson based on the given criteria, you can use the following nested Excel formula:\n\n=SUMPRODUCT((A2:A100=A2)*(B2:B100=\"Electronics\")*(MONTH(D2:D100)=1)*(C2:C100))\n\nExplanation: The SUMPRODUCT function in Excel allows you to perform multiple calculations and conditions within a single formula. Here's how the formula works:\n\n(A2:A100=A2) creates an array of TRUE/FALSE values indicating whether each cell in the range A2:A100 matches the salesperson's name in cell A2.\n(B2:B100=\"Electronics\") creates an array of TRUE/FALSE values indicating whether each cell in the range B2:B100 contains the product category 'Electronics'.\n(MONTH(D2:D100)=1) creates an array of TRUE/FALSE values indicating whether each cell in the range D2:D100 represents a date in the month of January.\n(C2:C100) is the range containing the sales amounts. The SUMPRODUCT function multiplies the corresponding elements of these arrays and then sums up the results. In this case, it multiplies the TRUE/FALSE values (1 for TRUE, 0 for FALSE) with the sales amounts, effectively summing only the sales that meet all the specified criteria.\n\nTip: Make sure the ranges A2:A100, B2:B100, C2:C100, and D2:D100 cover all the relevant data in your table. If your data extends beyond row 100, adjust the ranges accordingly. Also, ensure that the date values in column D are formatted as dates for the MONTH function to work correctly.",
"topic": "python_coding",
"instruction": "I have a table with sales data, including the salesperson's name in column A, the product category in column B, the sales amount in column C, and the date of sale in column D. I want to calculate the total sales amount for each salesperson, but only for sales of products in the 'Electronics' category that occurred in the month of January. Can you help me with the Excel formula to achieve this?"
},
{
"prompt": "Create a one-page website for an online learning platform called 'EduQuest' with the following features and sections: 1. A fixed navigation bar with links to course categories (Math, Science, Languages, Arts) and a search bar. 2. A hero section with a video background showcasing students learning online, a dynamic tagline that rotates between 'Learn at your own pace,' 'Discover new passions,' and 'Expand your horizons' every 3 seconds, and a 'Get Started' button leading to a course catalog. 3. A featured courses section displaying course cards with placeholders for course images, titles, instructors, and descriptions. 4. An interactive 'Learning Paths' section with a short quiz to determine learning styles and interests, and a button to start the quiz. 5. A 'Success Stories' section featuring testimonials from satisfied students, with placeholders for the testimonial text and student names. 6. A footer with links to the platform's blog, FAQ, privacy policy, and a 'Contact Us' button that opens a modal window with a contact form and customer support information. Include filler placeholder content for the video background, course cards, and testimonials. Embed the CSS styles within the <style> tag in the <head> section and place the JavaScript code within the <script> tag at the end of the <body> section. The JavaScript code should handle the dynamic tagline in the hero section, rotating through the different taglines every 3 seconds.",
"response": "<!DOCTYPE html>\n<html lang='en'>\n<head>\n <meta charset='UTF-8'>\n <meta name='viewport' content='width=device-width, initial-scale=1.0'>\n <title>EduQuest - Online Learning Platform</title>\n <style>/* ...CSS omitted for brevity, see prompt for full code... */</style>\n</head>\n<body>\n <header>\n <nav>\n <ul>\n <li><a href='#'>Math</a></li>\n <li><a href='#'>Science</a></li>\n <li><a href='#'>Languages</a></li>\n <li><a href='#'>Arts</a></li>\n <li><input type='text' placeholder='Search'></li>\n </ul>\n </nav>\n </header>\n <section class='hero'>\n <video src='placeholder-video.mp4' autoplay loop muted></video>\n <h1>Welcome to EduQuest</h1>\n <p id='tagline'>Learn at your own pace</p>\n <button>Get Started</button>\n </section>\n <section class='featured-courses'>\n <h2>Featured Courses</h2>\n <div class='course-card'>\n <img src='placeholder-course-image.jpg' alt='Course Image'>\n <h3>Course Title</h3>\n <p>Instructor: John Doe</p>\n <p>Course description goes here.</p>\n </div>\n <div class='course-card'>\n <img src='placeholder-course-image.jpg' alt='Course Image'>\n <h3>Course Title</h3>\n <p>Instructor: Jane Smith</p>\n <p>Course description goes here.</p>\n </div>\n </section>\n <section class='success-stories'>\n <h2>Success Stories</h2>\n <div class='testimonial'>\n <p>\"EduQuest helped me learn a new skill and advance my career. Highly recommended!\"</p>\n <p>- John Doe</p>\n </div>\n <div class='testimonial'>\n <p>\"I never thought I could learn a new language online, but EduQuest made it possible. Thank you!\"</p>\n <p>- Jane Smith</p>\n </div>\n </section>\n <footer>\n <a href='#'>Blog</a>\n <a href='#'>FAQ</a>\n <a href='#'>Privacy Policy</a>\n <button>Contact Us</button>\n </footer>\n <script>/* ...JS omitted for brevity, see prompt for full code... */</script>\n</body>\n</html>",
"topic": "python_coding",
"instruction": "Create a one-page website for an online learning platform called 'EduQuest' with the following features and sections: 1. A fixed navigation bar with links to course categories (Math, Science, Languages, Arts) and a search bar. 2. A hero section with a video background showcasing students learning online, a dynamic tagline that rotates between 'Learn at your own pace,' 'Discover new passions,' and 'Expand your horizons' every 3 seconds, and a 'Get Started' button leading to a course catalog. 3. A featured courses section displaying course cards with placeholders for course images, titles, instructors, and descriptions. 4. An interactive 'Learning Paths' section with a short quiz to determine learning styles and interests, and a button to start the quiz. 5. A 'Success Stories' section featuring testimonials from satisfied students, with placeholders for the testimonial text and student names. 6. A footer with links to the platform's blog, FAQ, privacy policy, and a 'Contact Us' button that opens a modal window with a contact form and customer support information. Include filler placeholder content for the video background, course cards, and testimonials. Embed the CSS styles within the <style> tag in the <head> section and place the JavaScript code within the <script> tag at the end of the <body> section. The JavaScript code should handle the dynamic tagline in the hero section, rotating through the different taglines every 3 seconds."
},
{
"prompt": "Core Python syntax",
"response": "Python uses variables, loops, functions, and error handling to build programs. Example: x = 5; for i in range(10): print(i); def foo(): return x; try: ... except: ...",
"topic": "python_coding",
"instruction": "Core Python syntax"
},
{
"prompt": "File handling",
"response": "Use open(), read(), write(), and with statements to safely handle files. Example: with open('file.txt', 'r') as f: data = f.read()",
"topic": "general",
"instruction": "File handling"
},
{
"prompt": "Modules & virtual environments",
"response": "Organize code with modules (import) and manage dependencies with virtual environments (venv, pip).",
"topic": "python_coding",
"instruction": "Modules & virtual environments"
},
{
"prompt": "Object-Oriented Programming",
"response": "Use classes and objects to encapsulate data and behavior. Example: class Dog: def __init__(self, name): self.name = name",
"topic": "python_coding",
"instruction": "Object-Oriented Programming"
},
{
"prompt": "Debugging",
"response": "Use print(), logging, and pdb to debug code. Check error messages and tracebacks.",
"topic": "python_coding",
"instruction": "Debugging"
},
{
"prompt": "APIs & HTTP requests",
"response": "Use requests or http.client to interact with web APIs. Example: import requests; r = requests.get('https://api.example.com')",
"topic": "general",
"instruction": "APIs & HTTP requests"
},
{
"prompt": "Automation",
"response": "Automate tasks with scripts, scheduling, and libraries like os, subprocess, and shutil.",
"topic": "python_coding",
"instruction": "Automation"
},
{
"prompt": "GUI apps (Tkinter)",
"response": "Build desktop apps with Tkinter. Example: import tkinter as tk; root = tk.Tk(); root.mainloop()",
"topic": "general",
"instruction": "GUI apps (Tkinter)"
},
{
"prompt": "Data analysis (pandas, numpy)",
"response": "Use pandas for dataframes and numpy for arrays. Example: import pandas as pd; df = pd.read_csv('data.csv')",
"topic": "python_coding",
"instruction": "Data analysis (pandas, numpy)"
},
{
"prompt": "AI/ML basics",
"response": "Use scikit-learn, TensorFlow, or PyTorch for machine learning. Example: from sklearn.linear_model import LinearRegression",
"topic": "general",
"instruction": "AI/ML basics"
},
{
"prompt": "Project architecture",
"response": "Organize projects with folders, modules, and clear structure. Use README and requirements.txt.",
"topic": "general",
"instruction": "Project architecture"
},
{
"prompt": "Testing",
"response": "Write tests with unittest or pytest. Example: import unittest; class TestFoo(unittest.TestCase): ...",
"topic": "python_coding",
"instruction": "Testing"
},
{
"prompt": "Packaging apps",
"response": "Package apps with setuptools or pyinstaller. Example: python setup.py sdist",
"topic": "python_coding",
"instruction": "Packaging apps"
},
{
"prompt": "Performance basics",
"response": "Profile code with timeit, cProfile. Optimize with efficient algorithms and data structures.",
"topic": "python_coding",
"instruction": "Performance basics"
},
{
"prompt": "Security basics",
"response": "Validate input, use secure libraries, and avoid hardcoding secrets.",
"topic": "general",
"instruction": "Security basics"
},
{
"prompt": "Real-world project templates",
"response": "Start projects with templates for CLI, GUI, web, or data apps.",
"topic": "general",
"instruction": "Real-world project templates"
},
{
"prompt": "Common errors and fixes",
"response": "Check syntax, indentation, imports, and error messages. Use try/except and debugging tools.",
"topic": "python_coding",
"instruction": "Common errors and fixes"
},
{
"prompt": "How to think like a programmer",
"response": "Break problems into steps, use pseudocode, and test incrementally.",
"topic": "python_coding",
"instruction": "How to think like a programmer"
},
{
"prompt": "desktop apps",
"response": "Build desktop apps with Tkinter, PyQt, or Kivy.",
"topic": "general",
"instruction": "desktop apps"
},
{
"prompt": "automation tools",
"response": "Automate with scripts, cron, and libraries like os and subprocess.",
"topic": "python_coding",
"instruction": "automation tools"
},
{
"prompt": "data scripts",
"response": "Write scripts for data processing with pandas, numpy, csv.",
"topic": "python_coding",
"instruction": "data scripts"
},
{
"prompt": "basic AI apps",
"response": "Build simple AI apps with scikit-learn, TensorFlow, or PyTorch.",
"topic": "general",
"instruction": "basic AI apps"
},
{
"prompt": "installers",
"response": "Package installers with pyinstaller or cx_Freeze.",
"topic": "general",
"instruction": "installers"
},
{
"prompt": "Async programming (asyncio, concurrency models)",
"response": "Use asyncio for async code. Example: async def foo(): await bar()",
"topic": "python_coding",
"instruction": "Async programming (asyncio, concurrency models)"
},
{
"prompt": "Multithreading vs multiprocessing deep dive",
"response": "Use threading for I/O-bound, multiprocessing for CPU-bound tasks.",
"topic": "automation",
"instruction": "Multithreading vs multiprocessing deep dive"
},
{
"prompt": "Network sockets",
"response": "Use socket module for TCP/UDP communication. Example: import socket; s = socket.socket()",
"topic": "general",
"instruction": "Network sockets"
},
{
"prompt": "Game development (Pygame)",
"response": "Build games with Pygame. Example: import pygame; pygame.init()",
"topic": "general",
"instruction": "Game development (Pygame)"
},
{
"prompt": "Web frameworks in depth (Django/FastAPI internals)",
"response": "Use Django for full-stack, FastAPI for async APIs. Learn models, views, routers.",
"topic": "general",
"instruction": "Web frameworks in depth (Django/FastAPI internals)"
},
{
"prompt": "Compilers & interpreters",
"response": "Understand Python's interpreter, bytecode, and how compilers work.",
"topic": "python_coding",
"instruction": "Compilers & interpreters"
},
{
"prompt": "Memory management internals",
"response": "Python uses automatic garbage collection. Manage memory with del, gc, and efficient structures.",
"topic": "python_coding",
"instruction": "Memory management internals"
},
{
"prompt": "C extensions for Python",
"response": "Extend Python with C for performance. Use ctypes, cffi, or write C modules.",
"topic": "python_coding",
"instruction": "C extensions for Python"
},
{
"prompt": "GPU programming",
"response": "Use libraries like numba, cupy, or PyCUDA for GPU acceleration.",
"topic": "general",
"instruction": "GPU programming"
},
{
"prompt": "Advanced ML (deep learning architectures)",
"response": "Build deep learning models with TensorFlow, PyTorch. Learn CNNs, RNNs, transformers.",
"topic": "general",
"instruction": "Advanced ML (deep learning architectures)"
},
{
"prompt": "Distributed systems",
"response": "Build distributed apps with multiprocessing, Celery, or Dask.",
"topic": "general",
"instruction": "Distributed systems"
},
{
"prompt": "Cryptography internals",
"response": "Use cryptography library for secure hashing, encryption, and protocols.",
"topic": "general",
"instruction": "Cryptography internals"
},
{
"prompt": "Python bytecode & VM internals",
"response": "Explore Python's bytecode with dis module. Learn about the Python VM.",
"topic": "python_coding",
"instruction": "Python bytecode & VM internals"
},
{
"prompt": "OS-level programming",
"response": "Use os, sys, and subprocess for OS interaction. Build system tools.",
"topic": "general",
"instruction": "OS-level programming"
},
{
"prompt": "Real-time systems",
"response": "Build real-time apps with threading, asyncio, and careful timing.",
"topic": "general",
"instruction": "Real-time systems"
},
{
"prompt": "Error handling best practices",
"response": "Always use try/except blocks, log errors, and provide user-friendly messages. Example: try: ... except Exception as e: print(f'Error: {e}')",
"topic": "python_coding",
"instruction": "Error handling best practices"
},
{
"prompt": "Advanced automation (scheduling, task orchestration)",
"response": "Automate complex workflows with sched, APScheduler, and Celery. Example: from apscheduler.schedulers.background import BackgroundScheduler",
"topic": "automation",
"instruction": "Advanced automation (scheduling, task orchestration)"
},
{
"prompt": "Security: authentication & authorization",
"response": "Implement authentication with libraries like Flask-Login, OAuth, and JWT. Use role-based access control for authorization.",
"topic": "general",
"instruction": "Security: authentication & authorization"
},
{
"prompt": "Code review and linting",
"response": "Use pylint, flake8, and black for code quality. Review code for readability, maintainability, and security.",
"topic": "python_coding",
"instruction": "Code review and linting"
},
{
"prompt": "Deployment (Docker, CI/CD)",
"response": "Deploy apps with Docker, GitHub Actions, and CI/CD pipelines. Example: docker build -t app .; docker run app",
"topic": "general",
"instruction": "Deployment (Docker, CI/CD)"
},
{
"prompt": "Documentation best practices",
"response": "Document code with docstrings, README files, and Sphinx. Example: def foo(): \"\"\"This function does X\"\"\"",
"topic": "python_coding",
"instruction": "Documentation best practices"
},
{
"prompt": "Version control (Git)",
"response": "Use Git for version control. Example: git init; git add .; git commit -m 'Initial commit'",
"topic": "general",
"instruction": "Version control (Git)"
},
{
"prompt": "Web scraping",
"response": "Scrape websites with BeautifulSoup and requests. Example: from bs4 import BeautifulSoup; soup = BeautifulSoup(html, 'html.parser')",
"topic": "web_development",
"instruction": "Web scraping"
},
{
"prompt": "Cloud basics (AWS, GCP, Azure)",
"response": "Use cloud SDKs to interact with AWS, GCP, or Azure. Example: import boto3; s3 = boto3.client('s3')",
"topic": "general",
"instruction": "Cloud basics (AWS, GCP, Azure)"
},
{
"prompt": "Data visualization",
"response": "Visualize data with matplotlib, seaborn, or plotly. Example: import matplotlib.pyplot as plt; plt.plot(data)",
"topic": "general",
"instruction": "Data visualization"
},
{
"prompt": "Unit testing advanced",
"response": "Write parameterized and mock tests with pytest. Example: @pytest.mark.parametrize('input,expected', [...])",
"topic": "api_parameters",
"instruction": "Unit testing advanced"
},
{
"prompt": "Refactoring code",
"response": "Refactor code to improve structure, readability, and performance. Use tools like Rope and PyCharm refactoring features.",
"topic": "python_coding",
"instruction": "Refactoring code"
},
{
"prompt": "Logging best practices",
"response": "Use logging module for structured logs. Example: import logging; logging.basicConfig(level=logging.INFO)",
"topic": "general",
"instruction": "Logging best practices"
},
{
"prompt": "Handling large datasets",
"response": "Process large datasets with Dask, PySpark, or chunking techniques. Example: for chunk in pd.read_csv('big.csv', chunksize=10000): ...",
"topic": "python_coding",
"instruction": "Handling large datasets"
},
{
"prompt": "API security",
"response": "Secure APIs with HTTPS, authentication, and input validation. Use Flask's request validation and JWT tokens.",
"topic": "general",
"instruction": "API security"
},
{
"prompt": "Mobile app basics (Kivy, BeeWare)",
"response": "Build mobile apps with Kivy or BeeWare. Example: from kivy.app import App",
"topic": "general",
"instruction": "Mobile app basics (Kivy, BeeWare)"
},
{
"prompt": "DevOps basics",
"response": "Automate deployment, monitoring, and scaling with tools like Ansible, Jenkins, and Docker Swarm.",
"topic": "automation",
"instruction": "DevOps basics"
},
{
"prompt": "Accessibility in apps",
"response": "Design accessible apps with keyboard navigation, screen reader support, and clear UI.",
"topic": "general",
"instruction": "Accessibility in apps"
},
{
"prompt": "Internationalization (i18n)",
"response": "Support multiple languages with gettext, Babel, and locale-aware formatting.",
"topic": "general",
"instruction": "Internationalization (i18n)"
},
{
"prompt": "Ethical AI principles",
"response": "Build AI systems that respect privacy, fairness, and transparency. Avoid bias and explain decisions.",
"topic": "general",
"instruction": "Ethical AI principles"
},
{
"prompt": "create python code",
"response": "To create Python code, define your requirements and use functions, classes, and modules. Example:\n\ndef main():\n # Your code here\n pass\n\nif __name__ == '__main__':\n main()",
"topic": "python_coding",
"instruction": "create python code"
},
{
"prompt": "Can you help me create a new word for the act of pretending to understand something in order to avoid looking ignorant or uninformed?",
"response": "How about the neologism \"fauxprehension\" to describe this concept?\n\nFauxprehension (fəʊprɪˈhɛnʃ(ə)n) - noun\nDefinition: The act of feigning understanding or comprehension of a topic, concept, or situation in order to avoid appearing ignorant, uninformed, or out of the loop. It is the pretense of knowledge or grasp of a subject matter, often employed in social or professional settings to maintain one's image or status.\n\nEtymology: The word \"fauxprehension\" is a blend of \"faux,\" which comes from the French word meaning false or fake, and \"comprehension,\" which means the action or capability of understanding something.",
"topic": "general",
"instruction": "Can you help me create a new word for the act of pretending to understand something in order to avoid looking ignorant or uninformed?"
},
{
"prompt": "The sun was going down and it was getting dark. The birds were making noise in the trees and there was wind. Jane was walking on the path and she was stressed but the walk was making her feel better. She saw a flower and thought it was pretty. It made her think about nature and stuff. She kept walking and felt better.",
"response": "Here are some suggestions to improve the text:\n\n- Vary sentence structure and length to create a more engaging rhythm. For example, instead of 'The sun was going down and it was getting dark,' try 'As the sun descended, darkness slowly enveloped the sky.'\n- Use more descriptive language to paint a vivid picture in the reader's mind. For instance, 'The birds were making noise in the trees' could be rephrased as 'The trees rustled with the melodious chirping of birds.'\n- Avoid vague words like 'stuff' and provide more specific details. Instead of 'She kept walking and felt better,' consider 'With each step, Jane felt her stress dissolve, replaced by a growing sense of tranquility.'\n- Show, don't tell. Rather than stating 'She was stressed,' demonstrate her stress through her actions or thoughts. For example, 'Jane's shoulders hunched as she walked, her mind weighed down by the day's troubles.'\n- Create a stronger connection between the natural surroundings and Jane's emotional state. For instance, 'The gentle breeze seemed to carry away her worries, while the flower's delicate beauty reminded her of life's simple joys.'\n\nHere's a fully edited version incorporating these suggestions:\n\nAs the sun descended, darkness slowly enveloped the sky. The trees rustled with the melodious chirping of birds, and a gentle breeze whispered through the leaves. Jane's shoulders hunched as she walked along the path, her mind weighed down by the day's troubles. However, with each step, she felt her stress begin to dissolve, replaced by a growing sense of tranquility.\n\nA flower caught her eye, its delicate petals a vibrant splash of color against the fading light. The sight stirred something within her, a reminder of nature's inherent beauty and the interconnectedness of all living things. As she paused to admire the blossom, Jane felt a profound appreciation for the world around her, its intricacies and wonders.\n\nContinuing down the path, her spirit lifted, the flower's simple elegance lingering in her thoughts. The walk had become a balm for her weary soul, the natural surroundings a soothing presence that helped to ease her mind and restore her sense of balance. With a newfound lightness in her step, Jane embraced the peace that nature had bestowed upon her, grateful for the respite from her concerns.",
"topic": "python_coding",
"instruction": "The sun was going down and it was getting dark. The birds were making noise in the trees and there was wind. Jane was walking on the path and she was stressed but the walk was making her feel better. She saw a flower and thought it was pretty. It made her think about nature and stuff. She kept walking and felt better."
},
{
"prompt": "I can haz cheeseburger?",
"response": "May I have a cheeseburger?",
"topic": "general",
"instruction": "I can haz cheeseburger?"
},
{
"prompt": "import random\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n-1):\n for j in range(n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n\nnumbers = [random.randint(1, 100) for _ in range(10)]\nprint(\"Unsorted array:\", numbers)\nsorted_numbers = bubble_sort(numbers)\nprint(\"Sorted array:\", sorted_numbers)",
"response": "This code demonstrates the implementation of the bubble sort algorithm, which is used to sort a list of numbers in ascending order. Let's break it down step by step:\n\n- The code starts by importing the 'random' module, which will be used to generate random numbers for the example.\n- The 'bubble_sort' function is defined, which takes an array (list) of numbers as input. This function will perform the sorting operation.\n- Inside the 'bubble_sort' function, the variable 'n' is assigned the length of the input array. This will be used to determine the number of iterations needed for sorting.\n- The first loop, controlled by the variable 'i', iterates 'n-1' times. This is because after 'n-1' passes, the largest number will be at the end of the array, so we don't need to compare it again.\n- The second loop, controlled by the variable 'j', iterates 'n-i-1' times. This is because after each pass, the largest number among the unsorted elements will be placed at the end, so we don't need to compare it in the next pass.\n- Inside the second loop, there is an if statement that compares adjacent elements in the array. If the element at index 'j' is greater than the element at index 'j+1', they are swapped. This ensures that the larger element moves towards the end of the array.\n- The swapping is done using the Python syntax 'arr[j], arr[j+1] = arr[j+1], arr[j]', which simultaneously assigns the values of 'arr[j+1]' to 'arr[j]' and 'arr[j]' to 'arr[j+1]'.\n- After all the iterations are complete, the sorted array is returned by the 'bubble_sort' function.\n- In the example code, a list of 10 random numbers between 1 and 100 is generated using a list comprehension: '[random.randint(1, 100) for _ in range(10)]'. The underscore '_' is used as a placeholder variable since we don't need the index values.\n- The unsorted array is printed to show the initial order of the numbers.\n- The 'bubble_sort' function is called with the 'numbers' array as input, and the sorted array is stored in the 'sorted_numbers' variable.\n- Finally, the sorted array is printed to display the numbers in ascending order.\n\nIn simpler terms, imagine you have a list of numbers that are out of order. The bubble sort algorithm works by comparing each number with the one next to it, and if they are in the wrong order, it swaps them. This process is repeated multiple times until the entire list is sorted. It's like bubbles rising to the surface, with the larger numbers gradually moving towards the end of the list in each pass.",
"topic": "python_coding",
"instruction": "import random\n\ndef bubble_sort(arr):\n n = len(arr)\n for i in range(n-1):\n for j in range(n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n\nnumbers = [random.randint(1, 100) for _ in range(10)]\nprint(\"Unsorted array:\", numbers)\nsorted_numbers = bubble_sort(numbers)\nprint(\"Sorted array:\", sorted_numbers)"
},
{
"prompt": "Silvermist Hollow, a charming village, was home to an extraordinary group of individuals. Among them was Dr. Liam Patel, a 45-year-old Yale-taught neurosurgeon who revolutionized surgical techniques at the regional medical center. Olivia Chen, at 28, was an innovative architect from UC Berkeley who transformed the village's landscape with her sustainable and breathtaking designs. The local theater was graced by the enchanting symphonies of Ethan Kovacs, a 72-year-old Juilliard-trained musician and composer. Isabella Torres, a self-taught chef with a passion for locally sourced ingredients, created a culinary sensation with her farm-to-table restaurant, which became a must-visit destination for food lovers. These remarkable individuals, each with their distinct talents, contributed to the vibrant tapestry of life in Silvermist Hollow.",
"response": "[\n {\n \"name\": \"Dr. Liam Patel\",\n \"age\": 45,\n \"profession\": \"Neurosurgeon\",\n \"education\": \"Yale\",\n \"accomplishments\": \"Revolutionized surgical techniques at the regional medical center\"\n },\n {\n \"name\": \"Olivia Chen\",\n \"age\": 28,\n \"profession\": \"Architect\",\n \"education\": \"UC Berkeley\",\n \"accomplishments\": \"Transformed the village's landscape with sustainable and breathtaking designs\"\n },\n {\n \"name\": \"Ethan Kovacs\",\n \"age\": 72,\n \"profession\": \"Musician and Composer\",\n \"education\": \"Juilliard\",\n \"accomplishments\": \"Graced the local theater with enchanting symphonies\"\n },\n {\n \"name\": \"Isabella Torres\",\n \"age\": null,\n \"profession\": \"Chef\",\n \"education\": \"Self-taught\",\n \"accomplishments\": \"Created a culinary sensation with her farm-to-table restaurant, which became a must-visit destination for food lovers\"\n }\n]",
"topic": "data_processing",
"instruction": "Silvermist Hollow, a charming village, was home to an extraordinary group of individuals. Among them was Dr. Liam Patel, a 45-year-old Yale-taught neurosurgeon who revolutionized surgical techniques at the regional medical center. Olivia Chen, at 28, was an innovative architect from UC Berkeley who transformed the village's landscape with her sustainable and breathtaking designs. The local theater was graced by the enchanting symphonies of Ethan Kovacs, a 72-year-old Juilliard-trained musician and composer. Isabella Torres, a self-taught chef with a passion for locally sourced ingredients, created a culinary sensation with her farm-to-table restaurant, which became a must-visit destination for food lovers. These remarkable individuals, each with their distinct talents, contributed to the vibrant tapestry of life in Silvermist Hollow."
},
{
"prompt": "Can you provide an example of a Python script that connects to a MySQL database, retrieves data from a table, and exports the data to a CSV file?",
"response": "Certainly! Below is an example of a Python script that connects to a MySQL database, retrieves data from a table, and exports the data to a CSV file:\n\n```python\nimport mysql.connector\nimport csv\n\n# Establish a database connection\nconnection = mysql.connector.connect(\n host='localhost', # Your host, e.g. localhost or IP address\n user='your_username', # Your MySQL username\n password='your_password', # Your MySQL password\n database='your_database' # Name of the database to use\n)\n\n# Create a cursor object using the cursor() method\ncursor = connection.cursor()\n\n# Define the SQL query to retrieve data from the table\ntable_name = 'your_table'\nsql_query = f'SELECT * FROM {table_name}'\n\n# Execute the SQL command\ncursor.execute(sql_query)\n\n# Fetch all the rows using the fetchall() method\nrows = cursor.fetchall()\n\n# Get the column headers from the cursor description\ncolumn_headers = [i[0] for i in cursor.description]\n\n# Specify the CSV file to write to\noutput_csv_file = 'output_data.csv'\n\n# Write the data to a CSV file\nwith open(output_csv_file, 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n # Write the column headers to the CSV file\n csv_writer.writerow(column_headers)\n # Write the data rows to the CSV file\n csv_writer.writerows(rows)\n\nprint(f'Data exported successfully to {output_csv_file}')\n\n# Close the cursor and the database connection\ncursor.close()\nconnection.close()\n```\n\n**Explanation:** \n1. **Import the necessary modules:** \n - `mysql.connector`: To connect to the MySQL database. \n - `csv`: To handle CSV file writing. \n2. **Establish a database connection:** \n - Use `mysql.connector.connect()` with the appropriate parameters (`host`, `user`, `password`, `database`) to connect to your MySQL database. \n3. **Create a cursor object:** \n - A cursor is created using the `cursor()` method of the connection object. It is used to execute SQL queries and fetch data. \n4. **Define the SQL query:** \n - Specify the SQL query to retrieve data from the desired table. In this example, we are selecting all columns from `your_table`. \n5. **Execute the SQL command:** \n - The `execute()` method of the cursor object is used to execute the SQL query. \n6. **Fetch the data:** \n - The `fetchall()` method retrieves all rows of the query result, returning a list of tuples. Each tuple represents a row in the table. \n7. **Get the column headers:** \n - The column headers are obtained from the cursor's description attribute, which contains metadata about the columns in the result set. \n8. **Specify the CSV file:** \n - Define the name of the output CSV file (`output_data.csv`) where the data will be exported. \n9. **Write data to CSV:** \n - Open the CSV file in write mode and create a CSV writer object. \n - Write the column headers to the CSV file using `writerow()`. \n - Write the data rows to the CSV file using `writerows()`. \n10. **Close the cursor and connection:** \n - It is important to close the cursor and the database connection using the `close()` method to free up resources. \n\n**Note:** \n- Make sure to replace the placeholder values (`localhost`, `your_username`, `your_password`, `your_database`, `your_table`) with your actual MySQL database connection details and the table you want to export. \n- The script exports the data to a CSV file in the same directory as the script. You can specify an absolute path for the CSV file if needed. \n- Ensure that you have the necessary permissions to access the MySQL database and the specified table.",
"topic": "python_coding",
"instruction": "Can you provide an example of a Python script that connects to a MySQL database, retrieves data from a table, and exports the data to a CSV file?"
},
{
"prompt": "Brand specs: This is a brand that focuses on creating high-quality, stylish clothing and accessories using eco-friendly materials and ethical production methods The brand targets environmentally conscious consumers aged 25-40 who value fashion, sustainability, and social responsibility. The brand identity should achieve the following goals: 1. Reflect the brand's commitment to sustainability, ethical practices, and environmental stewardship. 2. Appeal to the target audience by conveying a sense of style, quality, and trendiness. 3. Differentiate the brand from competitors in the sustainable fashion market. 4. Create a strong emotional connection with consumers and inspire them to make more environmentally friendly choices.",
"response": "Design Brief: Brand Identity for an Eco-Friendly Fashion Brand\n\nBrand Name Suggestion: 'Sēnsus' (Latin for 'sense' or 'perception,' evoking a sense of mindfulness and connection with the environment)\n\nLogo:\n- A minimalistic and modern logo that combines a stylized leaf or plant motif with a sleek, sans-serif typeface.\n- The leaf or plant element symbolizes the brand's commitment to sustainability and environmental stewardship, while the clean typography conveys a sense of sophistication and style.\n- The logo should be versatile and work well across various applications, including clothing tags, packaging, and digital platforms.\n\nColor Palette:\n- A neutral and earthy color palette that reflects the brand's eco-friendly ethos, such as shades of green, beige, and warm grays.\n- Accent colors like deep teal or mustard yellow can be used sparingly to add vibrancy and depth.\n- The color palette should evoke a sense of natural harmony and balance, while still being fashion-forward and appealing to the target audience.\n\nTypography:\n- A combination of a clean, modern sans-serif typeface for headlines and a complementary serif typeface for body copy.\n- The typography should be legible and visually appealing, conveying a sense of quality and sophistication.\n- Consistent use of typographic hierarchy and spacing will create a cohesive and organized brand identity.\n\nVisual Style:\n- A minimalistic and uncluttered visual style that emphasizes high-quality product photography and clean, modern layouts.\n- Incorporate natural elements, such as plant motifs or textures, to reinforce the brand's eco-friendly values and connection with nature.\n- Use negative space effectively to create a sense of openness and breathability, reflecting the brand's commitment to sustainability.\n\nTone of Voice:\n- The brand's tone of voice should be approachable, knowledgeable, and authentic.\n- Use language that educates and inspires consumers about the benefits of sustainable fashion and ethical production methods.\n- Incorporate a touch of sophistication and style to appeal to the target audience's fashion-conscious sensibilities.\n\nBrand Personality:\n- Eco-conscious and environmentally aware, yet stylish and fashion-forward.\n- Confident and passionate about promoting sustainable practices and ethical choices.\n- Inclusive and welcoming, inviting consumers to join a like-minded community committed to making positive changes.\n\nOverall, the brand identity for 'Sēnsus' should strike a balance between eco-friendly values and fashion-forward aesthetics, appealing to consumers who want to look stylish while making environmentally responsible choices. The cohesive visual and verbal elements should create a strong emotional connection with the target audience and inspire them to embrace a more sustainable lifestyle.",
"topic": "general",
"instruction": "Brand specs: This is a brand that focuses on creating high-quality, stylish clothing and accessories using eco-friendly materials and ethical production methods The brand targets environmentally conscious consumers aged 25-40 who value fashion, sustainability, and social responsibility. The brand identity should achieve the following goals: 1. Reflect the brand's commitment to sustainability, ethical practices, and environmental stewardship. 2. Appeal to the target audience by conveying a sense of style, quality, and trendiness. 3. Differentiate the brand from competitors in the sustainable fashion market. 4. Create a strong emotional connection with consumers and inspire them to make more environmentally friendly choices."
},
{
"prompt": "def example_function(n): for i in range(n): print(i) for j in range(n): for k in range(n): print(j, k)",
"response": "To analyze the time complexity of the given function example_function(n), we'll break it down into steps and consider the worst-case scenario.\n\nStep 1: Analyzing the first loop\n\nfor i in range(n):\n print(i)\nThis loop iterates n times and performs a constant-time operation (print(i)) in each iteration. Therefore, the time complexity of this step is O(n).\n\nStep 2: Analyzing the nested loops\n\nfor j in range(n):\n for k in range(n):\n print(j, k)\nThe outer loop iterates n times, and for each iteration, the inner loop also iterates n times. In each iteration of the inner loop, a constant-time operation (print(j, k)) is performed. Therefore, the time complexity of the nested loops is O(n * n) = O(n^2).\n\nStep 3: Combining the time complexities\nThe function example_function(n) consists of two steps: the first loop and the nested loops. The overall time complexity is the sum of the time complexities of each step.\n\nTime complexity of the first loop: O(n)\nTime complexity of the nested loops: O(n^2)\n\nTo determine the overall time complexity, we consider the dominant term, which is the term with the highest order of growth. In this case, O(n^2) dominates O(n).\n\nTherefore, the overall time complexity of the function example_function(n) is O(n^2).\n\nIn the worst-case scenario, when n is large, the nested loops will dominate the execution time, and the function will have a quadratic time complexity.",
"topic": "python_coding",
"instruction": "def example_function(n): for i in range(n): print(i) for j in range(n): for k in range(n): print(j, k)"
},
{
"prompt": "I've been using your email marketing platform for a few weeks, and I must say, the core features like campaign creation, email templates, and contact management are fantastic. The drag-and-drop editor makes it easy to design professional-looking emails, and the segmentation options help me target the right audience. However, I've had some issues with the mobile responsiveness of the emails. Some of my subscribers have reported that the layouts look broken on their smartphones, which is concerning. I'd love to see improvements in this area. Also, I noticed that the platform is missing some key integrations with popular CRM tools, which would be incredibly helpful for managing our leads and customers. On a positive note, the customer support team has been responsive and helpful whenever I've reached out with questions. Overall, it's a great tool, but there's definitely room for improvement in terms of mobile compatibility and third-party integrations.",
"response": "Categories:\n\nProduct Features and Functionality\nCore Features - Positive\n\nUser Experience and Design\nEase of Use - Positive\nVisual Design and Aesthetics - Positive\n\nMobile and Cross-Platform Compatibility\nMobile App Functionality - Negative\nResponsive Design - Negative\nDevice and OS Compatibility - Negative\n\nThird-Party Integrations and API\nIntegration Functionality and Reliability - Negative\n\nCustomer Support and Service\nResponsiveness and Availability - Positive\nIssue Resolution and Follow-up - Positive",
"topic": "python_coding",
"instruction": "I've been using your email marketing platform for a few weeks, and I must say, the core features like campaign creation, email templates, and contact management are fantastic. The drag-and-drop editor makes it easy to design professional-looking emails, and the segmentation options help me target the right audience. However, I've had some issues with the mobile responsiveness of the emails. Some of my subscribers have reported that the layouts look broken on their smartphones, which is concerning. I'd love to see improvements in this area. Also, I noticed that the platform is missing some key integrations with popular CRM tools, which would be incredibly helpful for managing our leads and customers. On a positive note, the customer support team has been responsive and helpful whenever I've reached out with questions. Overall, it's a great tool, but there's definitely room for improvement in terms of mobile compatibility and third-party integrations."
},
{
"prompt": "Phone Directory: John Latrabe, 555-232-1995, [john909709@geemail.com] Josie Lana, 555-759-2905, [josie@josielananier.com] Keven Stevens, 555-980-7000, [drkevin22@geemail.com] Phone directory will be kept up to date by the HR manager.",
"response": "john909709@geemail.com > josie@josielananier.com > drkevin22@geemail.com",
"topic": "general",
"instruction": "Phone Directory: John Latrabe, 555-232-1995, [john909709@geemail.com] Josie Lana, 555-759-2905, [josie@josielananier.com] Keven Stevens, 555-980-7000, [drkevin22@geemail.com] Phone directory will be kept up to date by the HR manager."
},
{
"prompt": "Can you extract the email addresses from the following text: 'For inquiries, contact us at support@example.com or sales@example.com. Visit our website at www.example.com for more information.'",
"response": "The email addresses extracted from the text are: support@example.com, sales@example.com",
"topic": "web_development",
"instruction": "Can you extract the email addresses from the following text: 'For inquiries, contact us at support@example.com or sales@example.com. Visit our website at www.example.com for more information.'"
},
{
"prompt": "How do I use the Messages API to create a message?",
"response": "To create a message using the Messages API, send a POST request to /v1/messages with a structured list of input messages and parameters. Example body:\n\n{\n \"max_tokens\": 100,\n \"messages\": [\n {\"role\": \"user\", \"content\": \"Hello, Claude\"}\n ]\n}\n\nThe 'messages' array contains objects with 'role' (user or assistant) and 'content' (text or content blocks). You can include multiple conversational turns. The 'max_tokens' parameter sets the maximum tokens to generate. For more details, see the user guide or API documentation.",
"topic": "api_parameters",
"instruction": "How do I use the Messages API to create a message?"
},
{
"prompt": "How do I use the top_p parameter and interpret the response format in the Messages API?",
"response": "The top_p parameter enables nucleus sampling, which controls the diversity of generated text by limiting the cumulative probability of considered tokens. Set top_p between 0 and 1 (e.g., 0.9). Use either temperature or top_p, not both.\n\nExample request:\n{\n \"top_p\": 0.8,\n \"messages\": [{\"role\": \"user\", \"content\": \"Hello!\"}]\n}\n\nThe response will be a message object with an id, content (an array of content blocks), and metadata such as stop_reason and usage. Example response:\n{\n \"id\": \"msg_123...\",\n \"content\": [{\"type\": \"text\", \"text\": \"Hi, I'm Claude.\"}],\n ...\n}\n\nCitations, tool use, and other block types may also appear in the content array depending on the model's output.",
"topic": "api_parameters",
"instruction": "How do I use the top_p parameter and interpret the response format in the Messages API?"
},
{
"prompt": "What is the response object structure for the Messages API?",
"response": "The response from the Messages API is a JSON object with fields like id, content (an array of content blocks), stop_reason, and usage. Example: {\"id\": \"msg_123...\", \"content\": [{\"type\": \"text\", \"text\": \"Hi, I'm Claude.\"}], ...}",
"topic": "api_response_format",
"instruction": "What is the response object structure for the Messages API?"
},
{
"prompt": "Can you show a sample API response for a message?",
"response": "Sample response: {\"id\": \"msg_abc...\", \"content\": [{\"type\": \"text\", \"text\": \"Hello!\"}], ...}",
"topic": "api_response_format",
"instruction": "Can you show a sample API response for a message?"
},
{
"prompt": "How do I use temperature and top_p in the API?",
"response": "Use either temperature or top_p to control randomness in text generation. Set one and leave the other at default. Both affect the diversity of generated text.",
"topic": "api_parameters",
"instruction": "How do I use temperature and top_p in the API?"
},
{
"prompt": "What does top_p do in the Messages API?",
"response": "top_p enables nucleus sampling, limiting the cumulative probability of considered tokens. Set between 0 and 1. Use either top_p or temperature, not both.",
"topic": "api_parameters",
"instruction": "What does top_p do in the Messages API?"
},
{
"prompt": "What is the difference between temperature and top_p?",
"response": "temperature scales the probability distribution for randomness; top_p limits the cumulative probability. Use one or the other for best results.",
"topic": "api_parameters",
"instruction": "What is the difference between temperature and top_p?"
},
{
"prompt": "Can you code in Python?",
"response": "Yes, I can write and explain Python code. For example, to print 'Hello, world!':\n\nprint('Hello, world!')\n\nLet me know what you want to build or automate in Python.",
"topic": "python_coding",
"instruction": "Can you code in Python?"
},
{
"prompt": "Write a Python function to add two numbers.",
"response": "def add(a, b):\n return a + b\n\n# Example usage:\nprint(add(2, 3)) # Output: 5",
"topic": "python_coding",
"instruction": "Write a Python function to add two numbers."
},
{
"prompt": "How do I reverse a string in Python?",
"response": "You can reverse a string in Python using slicing: s[::-1]. Example:\n\ndef reverse_string(s):\n return s[::-1]",
"topic": "python_coding",
"instruction": "How do I reverse a string in Python?"
},
{
"prompt": "Show me a Python script that prints numbers 1 to 5.",
"response": "for i in range(1, 6):\n print(i)",
"topic": "python_coding",
"instruction": "Show me a Python script that prints numbers 1 to 5."
},
{
"prompt": "How do I write a Python script to read a file?",
"response": "with open('file.txt', 'r') as f:\n data = f.read()\n print(data)",
"topic": "python_coding",
"instruction": "How do I write a Python script to read a file?"
},
{
"prompt": "hello",
"response": "Hello! Great to hear from you. How can I help you today?",
"topic": "greetings",
"instruction": "hello"
},
{
"prompt": "hi",
"response": "Hi there! What would you like to work on right now?",
"topic": "greetings",
"instruction": "hi"
},
{
"prompt": "hey",
"response": "Hey! I am here and ready to help. What do you need?",
"topic": "greetings",
"instruction": "hey"
},
{
"prompt": "good morning",
"response": "Good morning! Hope your day starts strong. What can I do for you?",
"topic": "greetings",
"instruction": "good morning"
},
{
"prompt": "good afternoon",
"response": "Good afternoon! I am ready when you are. What should we tackle?",
"topic": "greetings",
"instruction": "good afternoon"
},
{
"prompt": "good evening",
"response": "Good evening! Happy to assist. What are you working on tonight?",
"topic": "greetings",
"instruction": "good evening"
},
{
"prompt": "howdy",
"response": "Howdy! Nice to see you. How can I support you?",
"topic": "greetings",
"instruction": "howdy"
},
{
"prompt": "yo",
"response": "Yo! I am online and ready. What do you need help with?",
"topic": "greetings",
"instruction": "yo"
},
{
"prompt": "what's up",
"response": "Not much, just ready to help. What is up on your side?",
"topic": "greetings",
"instruction": "what's up"
},
{
"prompt": "hiya",
"response": "Hiya! Good to see you. What should we work on?",
"topic": "greetings",
"instruction": "hiya"
},
{
"prompt": "nice to meet you",
"response": "Nice to meet you too. Tell me what you want to build or solve.",
"topic": "greetings",
"instruction": "nice to meet you"
},
{
"prompt": "long time no see",
"response": "Long time no see! Glad you are back. What can I help with today?",
"topic": "greetings",
"instruction": "long time no see"
}
],
"metadata": {
"cleaned_at": "2026-02-11T14:57:37.100000Z",
"original_count": 152,
"cleaned_count": 150,
"removed": {
"short_prompt": 2
},
"topic_counts": {
"prompt_engineering": 9,
"api_parameters": 10,
"api_response_format": 5,
"python_coding": 52,
"creative_writing": 3,
"academic_writing": 1,
"general": 51,
"data_processing": 2,
"automation": 3,
"web_development": 2,
"greetings": 12
}
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394{ "version": "1.0", "project": "Codewiz AI Unified Training Tracks", "tracks": [ { "id": "text_core_tiny_model", "model_family": "tiny_causal_lm", "enabled": true, "handles_capabilities": [ "instruction_following", "conversation_management", "nlp_text_classification", "nlp_question_answering", "nlp_translation", "nlp_summarization", "nlp_intent_recognition", "nlp_entity_extraction", "reasoning_logical", "reasoning_multistep", "reasoning_pattern_recognition", "reasoning_deduction_inference", "math_reasoning", "complex_quant", "code_generation", "code_completion", "code_representation", "code_edit_refactor", "code_bug_detection", "code_multifile_reasoning", "debugging", "testing", "data_analysis", "data_science_ml", "predictive_regression", "predictive_classification", "predictive_time_series", "predictive_recommendation", "academic_research_support", "academic_writing", "humanized_writing", "originality_integrity_ethics", "domain_specialization_finance", "domain_specialization_health", "domain_specialization_coding", "tool_use_agentic", "tool_use_code_execution", "tool_use_api_calls", "tool_use_database_ops", "tool_use_command_execution", "web_information_retrieval", "web_source_synthesis", "image_workflow", "voice_workflow", "cv_object_detection", "cv_face_recognition", "cv_medical_image_analysis", "cv_ocr", "audio_speech_to_text", "audio_text_to_speech", "audio_speaker_recognition", "output_quality_controls" ], "training_inputs": [ "training_data.json", "knowledge_base.json", "capability_pack.jsonl", "multicapability_bootstrap.jsonl" ] }, { "id": "vision_perception_track", "model_family": "detector_or_vision_transformer", "enabled": true, "handles_capabilities": [ "cv_object_detection", "cv_face_recognition", "cv_medical_image_analysis", "cv_ocr" ], "note": "Specialized image model training track for direct pixel-level perception." }, { "id": "speech_audio_track", "model_family": "asr_tts_speaker_encoder", "enabled": true, "handles_capabilities": [ "audio_speech_to_text", "audio_text_to_speech", "audio_speaker_recognition" ], "note": "Specialized speech/audio model training track for acoustic signal learning." } ]}abilities.jsonAdded+175
adaptive_boost.jsonlAdded
ai_capability_file_map.jsonAdded+56
capability_pack.jsonlAdded
capability_pack.summary.jsonAdded+97
capability_registry.jsonAdded+73
config.pyAdded+23
dataset-metadata.jsonAdded+16
knowledge_base.jsonAdded
multicapability_bootstrap.jsonlAdded+33
requirements.txtAdded+21
tiny_local_model.ptAdded+3
tiny_model_core.pyAdded+280
tiny_model_data.pyAdded+1120
tiny_model_eval.pyAdded+467
tiny_model_stage1.jsonlAdded
tiny_model_stage2.jsonlAdded
tiny_training_history.jsonAdded
train_tiny_model.pyAdded+557
training_data.jsonAdded+927
training_tracks.jsonAdded+94