{"record":{"id":"0943537196cdea9e","repo":"crewAIInc/crewAI","slug":"an-error-occurred-while-training-the-crew-e","errorCode":null,"errorMessage":"An error occurred while training the crew: {e}","messagePattern":"An error occurred while training the crew: (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"lib/cli/src/crewai_cli/templates/crew/main.py","lineNumber":39,"sourceCode":"    try:\n        {{crew_name}}().crew().kickoff(inputs=inputs)\n    except Exception as e:\n        raise Exception(f\"An error occurred while running the crew: {e}\")\n\n\ndef train():\n    \"\"\"\n    Train the crew for a given number of iterations.\n    \"\"\"\n    inputs = {\n        \"topic\": \"AI LLMs\",\n        'current_year': str(datetime.now().year)\n    }\n    try:\n        {{crew_name}}().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)\n\n    except Exception as e:\n        raise Exception(f\"An error occurred while training the crew: {e}\")\n\ndef replay():\n    \"\"\"\n    Replay the crew execution from a specific task.\n    \"\"\"\n    try:\n        {{crew_name}}().crew().replay(task_id=sys.argv[1])\n\n    except Exception as e:\n        raise Exception(f\"An error occurred while replaying the crew: {e}\")\n\ndef test():\n    \"\"\"\n    Test the crew execution and returns the results.\n    \"\"\"\n    inputs = {\n        \"topic\": \"AI LLMs\",\n        \"current_year\": str(datetime.now().year)","sourceCodeStart":21,"sourceCodeEnd":57,"githubUrl":"https://github.com/crewAIInc/crewAI/blob/754d7323beb2fd042e33444a115ea2d5a47193f0/lib/cli/src/crewai_cli/templates/crew/main.py#L21-L57","documentation":"Wrapper in the crew template's train() function. It catches every exception from {{crew_name}}().crew().train(n_iterations, filename, inputs) and re-raises it as a generic Exception prefixed with 'An error occurred while training the crew'. Training runs the crew n_iterations times and stores pickled memories; failures can come from kickoff, memory pickling to the filename, or invalid arguments.","triggerScenarios":"Running `uv run train <n> <file>` where the underlying crew kickoff fails (LLM/API errors), the filename is not writable, n_iterations is not a valid int (int(sys.argv[1]) raises ValueError caught here), or sys.argv[2] is missing (IndexError caught here).","commonSituations":"Developer runs `uv run train 5` without the filename argument; passes a non-numeric iteration count; trains in an environment where the LLM key is unset; writes the pickle to a read-only directory.","solutions":["Check the suffix after the colon for the real exception; it is usually IndexError (missing filename argv) or ValueError (non-int iterations) from int(sys.argv[1]).","Invoke training with both positional args: `uv run train 5 memory.pkl`.","Ensure the crew runs cleanly first (`uv run run`) — training reuses kickoff, so any run failure will surface here too.","Confirm the output filename path is writable and ends with .pkl."],"exampleFix":"# before\ntry:\n    MyCrew().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)\nexcept Exception as e:\n    raise Exception(f\"An error occurred while training the crew: {e}\")\n\n# after\nif len(sys.argv) < 3:\n    raise SystemExit(\"Usage: train <n_iterations> <filename.pkl>\")\nMyCrew().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)","handlingStrategy":"validation","validationCode":"import sys\nif len(sys.argv) < 3:\n    raise SystemExit(\"Usage: train <n_iterations:int> <filename.pkl>\")\nn = int(sys.argv[1])\nassert n > 0, \"n_iterations must be positive\"\nassert sys.argv[2].endswith(\".pkl\")","typeGuard":"def is_valid_train_args(argv: list[str]) -> bool:\n    return (\n        len(argv) >= 3\n        and argv[1].isdigit()\n        and int(argv[1]) > 0\n        and argv[2].endswith(\".pkl\")\n    )","tryCatchPattern":"try:\n    MyCrew().crew().train(n_iterations=n, filename=fn, inputs=inputs)\nexcept Exception:\n    logging.exception(\"training failed\")\n    raise","preventionTips":["Always invoke as `uv run train N file.pkl` with both args","Verify a plain run succeeds before training","Validate argv count/types at the top of main.py instead of letting IndexError reach the wrapper"],"tags":["crewai","cli","template","training"],"backgroundTag":null,"analyzedSha":"754d7323beb2fd042e33444a115ea2d5a47193f0","analyzedAt":"2026-08-15T04:06:56.746Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}